简体   繁体   中英

Laravel 4 - get Records where entry in N:N Relation exists

I have some trouble with an Eloquent Query.

I Have 3 Tables:

products

  • ID
  • NAME

media

  • ID
  • FILE

product_media

  • PRODUKT_ID
  • MEDIA_ID

Now i am trying to an get random result set from the Product table, but only records where an media file exists.

Something like this (does not work..)

Product::orderByRaw("RAND()")->media()->wherePivot('file', '=!' , '')->take(10)->get();

You should use:

Product::orderByRaw("RAND()")->has('media')->take(10)->get();

It will take all products that has at least one media. I assume that you store in product_media only entries where file != ''

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