0

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?

TylerH
  • 20,799
  • 66
  • 75
  • 101
Mav
  • 1,087
  • 1
  • 15
  • 37

2 Answers2

1

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

Patrick Schocke
  • 1,493
  • 2
  • 13
  • 25
1

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

Jignesh Joisar
  • 13,720
  • 5
  • 57
  • 57
  • It works, but stops working when I combine it with `select`. How can I achieve `Log::with('hash:id,text')->select('log')->first()`? As this turns `hash` null. – Mav Dec 14 '18 at 14:24
  • @Mav u need to select also relational columns in parent table otherwise it wiill give you null data..(i also mention in answer dear) – Jignesh Joisar Dec 14 '18 at 18:43