Support the ongoing development of Laravel.io →
posted 9 years ago
Eloquent
Last updated 2 years ago.
0

Are you sure your query is correct? You need a method on the end that executes the query, such as get().

Also, is there a reason you're doing this in a join rather than a relationship on your model(s)?

$resultList = Modelname::join('child_table', 'parent.id', '=', 'child.parent_id')
  ->where('child.some_field','=', 'something')
  ->get();
Last updated 9 years ago.
0

Thank you AndrewBNZ for your help.

Yes, I am pretty sure, that my query is correct. I get a correct result. You are right. I have used the ->get() statement but did not write it down in my example.

I will try to explain my problem with other words.

Assume I have two models with selfexplaning names.

  • parent (id, name)
  • child (id, parent_id, name)

Inside the models I define the relations like

Model 'Parent':

public function children()
{
       return $this->hasMany('Child');
 }

Model 'Child'

  public function myparent()
  {
         return $this->belongsTo('Parent');
   }

Now I want to select all parents with a specific condition in the child table. This code works (just an example without condition):

$resultList = Parent::all();
foreach ($resultList as $item)
      foreach ($item->children as $c)
           echo $c->name;

But if I try the following:

  $resultList = Parent::join('child', 'parent.id','=','child.parent_id')
       ->where('child.field','=','something')
       ->get();
  foreach ($resultList as $item)
       foreach ($item->children as $c)
            echo $c->name;

I will get the correct number and models of type "parent". But in the inner foreach loop the relation method "children" always returns nothing. Even if I call an $item->load('children') .

Last updated 9 years ago.
0

I solved it by using a subquery.

  $resultList = Parent::whereIn( ....)

It seams that the relations are not populated / executed when part of a join.

0

Sign in to participate in this thread!

Eventy

Your banner here too?

iwen65 iwen65 Joined 17 Jan 2015

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2024 Laravel.io - All rights reserved.