0

I have two database tables items and measurement_units - item has measurement unit.

Now the problem is I want to select a particular column from items and some column from measurement_unit. I want to use Eager loading

e.g.

$items_with_mu = Item::with("measurement_unit")->select(["item_name", "item_stock"])->first();

When accessing measurement_unit. It returns null. Without the select function it returns data(measurement_unit).

$items_with_mu->measurement_unit;

can anyone help me and sorry for my English.

1
  • But I need to select column. I got my answer. BDW thanks for reply. Commented Mar 19, 2019 at 12:10

2 Answers 2

1

Try this

Item::with(['measurement_unit' => function($q) { 
           $q->select('id','unit_column');   //specified measurement_unit column
      }])
     ->select('id','measurement_unit_id','item_name')
     ->get();

If your laravel version is >=5.5 then you can write in a single line

Item::with('measurement_unit:id,unit_column')
     ->select('id','measurement_unit_id','item_name')
     ->get()
Sign up to request clarification or add additional context in comments.

3 Comments

should be work select foreign key measurement_unit_id. check latest code
Glade to help you. you should check updated answer if your laravel version is >=5.5
now I got the point where I am missing. without foreign key how a table can be join.
0

You have to select the primary column of the main model like below.

 items_with_mu = Item::with("measurement_unit")->select(["item_name", "item_stock", "primary_key"])->first();

6 Comments

Can you please paste your relationship method?
Also database structure as well.
primary_key should be foreing key. after adding foreign key it works.
@ThataL I'm talking about the primary column of Item model.
Ok my mistake (primary key of another model). accept my edit I will vote as answer. Description is minimum that's why it make me confused.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.