Thursday, March 2, 2017

How to query parent-childe relationship in Laravel in one SQL query

I am trying to get two related models in laravel using Eager Loding as per documentation.

http://ift.tt/2mcEgnb

My models are:

class Lead extends Model {
  public function session() {
    return $this->hasOne('App\LeadSession');
  }
}

class LeadSession extends Model {
  public function lead() {
    return $this->belongsTo('App\Lead');
  }
}

I want to execute:

select * from lead_sessions as s 
inner join lead as l 
on l.id = s.lead_id 
where s.token = '$token';

Here is the php code I am trying:

$lead = Lead::with(['session' => function ($q) use ($token) {
  $q->where('token','=',$token);ngo and I want to replicate the behavior of select_related in Django.
}])->firstOrFail();

print($lead->session->id);

I have also tried:

$lead = Lead::whereHas('session', function($q) use ($token) {
  $q->where('token','=',$token);
})->firstOrFail();

print($lead->session->id);

and

$session = LeadSession::with('lead')->where('token',$token)->firstOrFail();

print($session->lead->id);

In all three cases I get two queries executed, one for the leads table, and another for the lead_sessions table.

Is this possible to do it in Eloquent?

I don't want to use the Query Builder because I want to use the models afterwards.

I am coming from Python and Django and I want to replicate the behavior of select_related in Django.




via Martin Taleski

Advertisement