Jack The Baker
Jack The Baker

Reputation: 1903

Laravel get data in through relation

I use this hasOneThrough to get user through post to display result inf file:

Controller

File::where('agent_id', $user->id)
                ->with(['user' => function ($q) {
                    $q->select('name','phone');
                }])->get(['post_id', 'status']);

Model

// __________________________ related__|__through_|_1key_|_2key_|_lkey_|_seclkey

return $this->hasOneThrough('App\User', 'App\Post', 'id', 'id', 'post_id', 'user_id');

// ___________________________________________^ > want to get `hash` from `post`

This work good, but now I need one item from post called hash in this result, is it possible to get any data from through (Post table). Already able to get any data from file and user but how can I get data from through (Post table) ?

I don't know how can do this, so I searched and nothing found, so I couldn't try anything.

Upvotes: 0

Views: 72

Answers (2)

Pedram
Pedram

Reputation: 16615

You should use hasOne in your model:

public function post(){
    return $this->hasOne('App\Post', 'id', 'post_id');
}

And in your controller you can use eager loading but I noticed you get null, in order for this to work, you also have to select the id:

$files = File::where('agent_id', $user->id)->with('user:phone,name', 'post:id,hash')->get(['post_id', 'status']);

Upvotes: 1

Alberto
Alberto

Reputation: 12949

If your File table has a post_id, and between posts and files table there is a One to Many relation, just declare a new relation:

public function post(){
   return $this->belongsTo('App\Post', 'post_id', 'id');
}

Also keep in mind that if inside a with you want to select only specific fields, you can just do ->with('user:phone,name')

Upvotes: 1

Related Questions