Laravel eager loading with value of current model?

Viewed 488

Hi guys is it possible to do this in an eager loading?

Client::with(['relationship' => function($query){ 
     $query->whereBetween('created_at', [$client->failed_date, Carbon::now()->endOfDay()])
}])->get();

Basically I want to put the failed_date column from my CLIENT model into the eager loading query.

1 Answers

Since all types of Eloquent relationships are defined via methods, you may call those methods to obtain an instance of the relationship without actually executing the relationship queries. In addition, all types of Eloquent relationships also serve as query builders, allowing you to continue to chain constraints onto the relationship query before finally executing the SQL against your database.

For example.

$clients = Client::where('status', 1)->get();

foreach($clients as $client) {
    $relationships = $client->relationship()
        ->whereBetween('created_at', [$client->failed_date, $client->pass_date]);
}

This way you can solve your problem.

If you're trying to eagerly load your relationships, As eager load will perform a separate query you don't have direct access to the parent table, so you need to join it.

public function relationship()
{
    return $this->belongsTo(Client::class)
        ->selectRaw('clients.*')
        ->join('relationships', 'clients.id', '=', 'relationships.client_id')
        ->whereRaw("....");
}
Related