Question

I have two tables Models and Cars related as per cars.model_id = model.id. Car belongsTo Model and Model hasMany Cars.

When I would like to do a search based on the Model name in the cars table I do the following query:

Car::join('models', 'cars.model_id', '=', 'models.id)
   ->where('models.name', 'like', '%'.$term.'%')
   ->paginate($_ENV['ITEMS_PER_PAGE']);

My problem is that Eloquent ORM of Laravel in that case returns the model.id as the main id, so resultset will have the model.id as Id instead of the Car.id. Any solution for that?

As per the documentation of Laravel, I thought that Eloquent would assume correctly the table Id without any help:

Note: Eloquent will also assume that each table has a primary key column named id. You may define a primaryKey property to override this convention. Likewise, you may define a connection property to override the name of the database connection that should be used when utilizing the model.

Was it helpful?

Solution

Just don't SELECT id or none of the models fields if you don't need them (where clause will work anyway)

Car::join('models', 'cars.model_id', '=', 'models.id')
 ->where('models.name', 'like', '%'.$term.'%')
 ->paginate($_ENV['ITEMS_PER_PAGE'], ['cars.*','models.fieldsYouNeedOrNothing']);

side note: You can use whereHas() instead of join to do it more 'eloquent' way if you really don't need joined table's fields:

Car::whereHas('models', function ($query) use ($term) {
   $query->where('models.name', 'like', '%'.$term.'%');
})->paginate($_ENV['ITEMS_PER_PAGE']);

This will run subquery on models table and leave you without any worries about the keys.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top