Chris
Chris

Reputation: 14218

eloquent refer to a column of a related a model

I have three tables:

categories
id, title

products
id, name

categories_products
id, category_id, product_id

I have also setup the according models and relationships (both have belongsToMany of the other)

Now I want to get all products belonging to a category

Category::where('title','Electronics')->first()->products()->limit(10)->get(['products.name']);

which works fine, but I also want to include the category title for each product as well:

Category::where('title','Electronics')->first()->products()->limit(10)->get(['products.name','category.title']);

However it returns: Column not found category.title

I thought that the relation would take care of it.

EDIT: Models -->

Category:

class Category extends Model
{

    protected $fillable = array('title');

    public function products()
    {
        return $this->belongsToMany('Product', 'categories_products', 'category_id', 'product_id');
    }
}

class Product extends Model
{

    protected $fillable = array('name');

    public function categories()
    {
        return $this->belongsToMany('Category', 'categories_products', 'product_id', 'category_id');
    }
}

Upvotes: 0

Views: 502

Answers (1)

Eric Tucker
Eric Tucker

Reputation: 6345

The reason you're getting the error is because get() works just like select() and because you're running the category query and then running the product query after there is no categories table to reference for the select.

Look into Eager Loading. It will help with a lot of these kinds of issues. Your query can be written as:

Product::select('id', 'name')
->with(['categories' => function($query) {
    return $query->select('id', 'title');
}])
->whereHas('categories', function($query) {
    return $query->where('title', 'Electronics');
})
->limit(10)
->get();

Because we are lazy loading you NEED the id column on each model so Laravel knows where to attach the relationships after the queries are run.

The with() method above will eager load the categories relationship and the whereHas() method puts a relationship constraint on the current query.

UPDATE

Similar query from Category model:

$category = Category::where('title','Electronics')
    ->with(['products' => function($query) {
        return $query->select('id', 'name')->limit(10);
    }])
    ->first(['id', 'title']);

Then access the products with:

$category->products

Upvotes: 1

Related Questions