butifarra's avatar

Search through a pivot table many to many relationship

Hi! I tried this for 8 hours straight, so I give up. I have three models: Crop: id name

Variety: id plant_id name

Plant id name

Each crop can have n varieties, so I created the pivot table crop_variety with these fields: crop_id variety_id

And in crop model I have this:

public function varieties(): BelongsToMany { return $this->belongsToMany(Variety::class) }

That works, no problem, I can get all the varieties and their names. But I need a plants() belongsToMany method, that is, all the plants and their names the crop belongs to through the variety model. I read all the documentation about this, it says you can create a model for the pivot table but not how to use it. https://laravel.com/docs/11.x/eloquent-relationships#defining-custom-intermediate-table-models I googled for examples, but I found nothing like my case. If anyone can lend a hand, I will be very grateful.

0 likes
2 replies
Shivamyadav's avatar

Are you trying to execute a search query to the pivot table to find some data , there you stuck? Right

butifarra's avatar

@Shivamyadav I am making a filter search, using the same word to search in all fields of Crop and the related tables. Does something like "belongsToThrough" exist for many to many relationships? I use in other place hasManyThrough, but in a normal chain 1 to n to 1 to n.

Please or to participate in this conversation.