简体   繁体   中英

Laravel 5.6 Multi-relation eloquent query

So I have the following database structure:

  • sport
  • camera
  • sport_has_camera

With a relation in sport_has_camera .

So the table sport_has_camera holds the ID from both the sport and the camera.

Now I have a model called Sport.php and Camera.php . I want to be able to do: Sport::where('name' , $sport_name)->firstOrFail()->cameras what would return all the camera's of that sport (linked in the database. Now I have this in Sport.php :

public function cameras()
    {
        return $this->hasMany('App\Camera');
    }

But that doesn't do what I want, how can I resolve this?

You're looking for belongsToMany

https://laravel.com/docs/5.6/eloquent-relationships#many-to-many

return $this->belongsToMany(Camera::class, 'sport_has_camera', 'sport_id', 'camera_id');

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