Mav
Mav

Reputation: 1190

How to get a part of a belongsTo relationship in Laravel?

I have a model called Log. It has a foreign key called hash_id, and a belongsTo relationship to App\Hash.

I understand that I can retrieve the corresponding hash entry by calling Log::with('hash') as mentioned here. What I'd like to do is retrieve specific rows of the corresponding hash column instead of every one of them. So something like Log::with('hash', ['only' => 'name']). This is because I'm sending the data over AJAX, and don't want to send a lot of unnecessary columns with it. How can I do this?

Upvotes: 0

Views: 529

Answers (2)

Jignesh Joisar
Jignesh Joisar

Reputation: 15095

you can do by two ways

using anonymous function

Log::with(['hash' => function($query) { 
    return $query->select('id','text');
}])->get();

second way

  Log::with('hash:id,text')->get();

Remember one thing you will need to select relational columns or else it will not work

more information read this article

Upvotes: 1

Patrick Schocke
Patrick Schocke

Reputation: 1491

You have to write all the columns with a :

Log::with('hash:id,text')

This would return only the id and the text.

As a sidenote: You need to select the foreign key, otherwise the relation is empty

Here you can read more about it

Upvotes: 1

Related Questions