gibAlex gibAlex - 7 months ago 30
PHP Question

Laravel RelationShip( join with where)

i need help on laravel 5(use Eloquent)

I have 2 tables

Model Driver
drivers


  • id

  • company



Model DriverOnline
drivers_online


  • id

  • name

  • driver_id



I need seatch result on (commany=1 and driver_id=driver.id) help me!

Answer

If you want to only fetch Driver based on a condition, you can just do this:

Driver::with('online')->where('company', 1)->get();

If the clause is on the relationship, use with and specify a query on that.

$company = 1;
$drivers = Driver::with(['online' => function($query) use ($company)
{
    $query->where('company', $company);
}]);

See "Eager Load Constraints":
https://laravel.com/docs/5.0/eloquent

Take note of my use. This allows you to include variables from the scope into your Closure instance.

And be aware, if you use either solution, you must set up a relationship. Consult the link I shared with more information on that.

Edit: As per our conversation.

$drivers = Driver::where('company_id','=',1)
    ->with('driversOnline')
    ->whereHas('driversOnline', function($query) {
        $query->where('online','=',1);
    })
    ->get();