Search code examples
laravelmany-to-manyrelationship

Laravel - SQL query equals the value of id to null in many to many relationship


In model I have:

class Car extends Model
{
    public function users()
    {
        return $this->belongsToMany(User::class, 'car_user', 'car_id', 'user_id');
    }
}

And in my controller I have:

\DB::enableQueryLog();
$cars = Car::with('users')->get();
dd(\DB::getQueryLog());

The queries executed are:

array:2 [▼
  0 => array:3 [▼
    "query" => "select * from `cars`"
    "bindings" => []
    "time" => 0.62
  ]
  1 => array:3 [▼
    "query" => "select `users`.*, `car_user`.`user_id` as `pivot_user_id`, `car_user`.`car_id` as `pivot_car_id` from `users` inner join `car_user` on `users`.`user_id` = `car_user`.`car_id` where `car_user`.`user_id` in (?)"
    "bindings" => array:1 [▼
      0 => null
    ]
    "time" => 0.6
  ]
]

The problem is that the bindings value in second query is null. I want to get all cars and iterate into each of them and get as many users each car has.

How can I do that?

Edit table schema:

car_user: car_id user_id

cars: car_id car_code price

users: user_id user_type username password

Thanks


Solution

  • Since you are using custom primary keys, you have to specify them in your models:

    class Car extends Model
    {
        protected $primaryKey = 'car_id';
    }
    
    class User extends Model
    {
        protected $primaryKey = 'user_id';
    }