Home > front end >  Laravel hasOne can't only one attribute from the relation model
Laravel hasOne can't only one attribute from the relation model

Time:05-18

I have a Model called User That has one to many relation with orders I'm trying to get using an eloquent relation the first order date he did

I tried adding in the User Model

public function firstOrderDate(){
return $this->hasOne(Order::class)->oldest();
}

My Query

User::whereHas('firstOrderDate')->with('firstOrderDate')->get()

it's returning the Whole Order model I even tried to add select('date') it's returning null now

CodePudding user response:

you can do it by creating a relationship for first order and create accessor for first_order date

public function firstOrder(){
    return $this->hasOne(Order::class)->oldestOfMany();
}

public function getFirstOrderDateAttribute($value){
    !empty($this->firstOrder) ? $this->firstOrder->created_at : '';
}

Your Query will be:

User::whereHas('firstOrder')->selectRaw('users.*, "" as first_order_date')->get();

CodePudding user response:

it's returning the Whole Order model I even tried to add select('date') it's returning null now to work properly relation need relation key to be selected

User::whereHas('firstOrderDate')->with(['firstOrderDate' => function($q) {
    $q->select('user_id', 'date_field');
})->get()

then you will get shrinked Order model with only selected fields like this

{
    'id': 1,
    // other fields
    'firstOrderDate': {
        'user_id': 1,
        'date_field': '1970-01-01 00:00:00'
    }
}

CodePudding user response:

This could do the job (didn't test it):

public function firstOrderDate(){
    return $this->hasMany(Order::class)->oldest()->first()->firstOrderDate;
}

You said, you have a one to many relationship with the order table, so use hasMany, sort by oldest first and return first Model.

  • Related