daveb2's avatar

Trying to match a property of an eager-loaded model using ::with()

Hi,

I have two models, Page and Category, which are related as follows:

Page.php

public function category(): BelongsTo
	{
		return $this->belongsTo(Category::class, 'category_id');
	}

Category.php

	/**
	 * Get the pages for this category
	 */
	public function pages(): HasMany
	{
		return $this->hasMany(Page::class);
	}

In a controller I have:

$search = 'mytest';// known to be a partial match for >0 categories associated with pages
$pages = Page::with('category')->when($search ?? false, function($q) use ($search) {
	return $q->where(function (Illuminate\Database\Eloquent\Builder $q) use ($search) {
		$q->orWhere('name', 'like', '%' . $search . '%');
	});
})->get();

However, when I run this query I get:

 Illuminate\Database\QueryException  SQLSTATE[42S22]: Column not found: 1054 Unknown column 'name' in 'where clause' (Connection: mysql, SQL: select * from `pages` where (`name` like %mytest%) and `pages`.`deleted_at` is null).

Is there a trick to getting queries to work via BelongsTo() relationships? Or is this functionality not possible?

If this isn't possible, what is best practice for this kind of query? Do I need to pre-search a collection of Categories myself and then do a Page::whereIn('name', $categories->pluck('name')->toArray()) ?

0 likes
1 reply

Please or to participate in this conversation.