PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Wednesday, January 19, 2022

[FIXED] Laravel eloquent, select model with relationship in a single query

 January 19, 2022     eloquent, laravel-5     No comments   

Issue

Let's say we have many-to-many relationship for models Car and Driver:

class Car extends Model {...}

class Connection extends Model
{
    public function car()
    {
        return $this->belongsTo('app\Car');
    }

    public function driver()
    {
        return $this->belongsTo('App\Driver');
    }
}

class Driver extends Model {...}

Now I'd like to query for Cars which can be driven by John. With QueryBuilder this is quite simple:

 $query = DB::table('cars')
        ->join('connections', 'cars.id', '=', 'connections.car_id')
        ->join('drivers', 'connection.driver_id', '=', 'drivers.id')
        ->where('drivers.name', 'like', 'John')->select('cars.*')->get();

This will generate a single SQL query which is more or less exactly would I'd expect.

The rest of the application uses Eloquent for DB querying and so I'd like to rewrite this part with Eloquent. I gave it multiple tries but I can't generate a single query with plain JOINs (not subqueries). Is it possible?


Solution

You can use whereHas eloquent function to get Cars which can be driven by John

$cars = Car::whereHas('drivers',function($query) use ($driver_name){
       $query->where('name','like','%'.$driver_name.'%');
})->get();

for models you can use which @Idob write to his answer.



Answered By - seyyed sina
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing