简体   繁体   中英

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, eg "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 = \App\Category::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 = \App\Category::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!

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

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

Example:

\App\Category::where('url', $category)->first()->products

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM