Skip to content
Advertisement

Laravel Eloquent ORM: Select from two tables without using find() possible?

Basically I would like to run a very simple database select query accross two tables in mysql considering a one-to-many-relationship.

categories: This table contains all product-categories. The primary key is “id”. It has one column “url” which holds the string how to access this category, e.g. “greeting-cards”.

products: This table contains all products whereas each product has one category id. The primary key is “id”. It has one column “category_id” which represents the id of the category the product corresponds to.

So, according to the documentation of Eloquent ORM, I did this:

$products = AppCategory::find($CATEGORY_ID)->products);

And it’s is working like a charm.

Now the problem is: When accessing a webpage, the URL doesn’t look like this:

www.domain.tld/categories/123

However, it looks like this due to SEO:

www.domain.tld/categories/greeting-cards

Therefore, I modified the database query like this:

$products = AppCategory::where('url', $category)->products);

But this does not work! Do I see it correctly that I have to use find() and placing a where() method is wrong here? Are there any other approaches to do this in Eloquent? I don’t like to use a second database query to get the ID of the corresponding category url and then paste this id into the database query… I know this is possible, but I think there should be more elegant ways to this in Eloquent?

Thank you so much!

Advertisement

Answer

You have to retrieve the model in order to use its relations.

If you want to use where() just call first():

Example:

AppCategory::where('url', $category)->first()->products

More methods are available at Laravel’s docs: Retrieveing single models.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement