简体   繁体   中英

Pivot table with more than two foreign ids

So I have a table, cities

城市表

Second table is movies ,

在此处输入图像描述

And the third table is theatres

在此处输入图像描述

I have a Pivot table which connects all three of these.

在此处输入图像描述

What I am trying to achieve is, to get only those theatres where city_id and movie_id are a certain value. This is my controller

class MovieController extends Controller
{
    public function test(){
        $city_id=1;
        $movie_id=1;
        $th=Movie::where('id',$movie_id)->first();
        dd($th->theatre);
    }
}

I want all the theatres where movie_id=1 and city_id=1

Movie Model

class Movie extends Model
{
    use HasFactory;
    public function theatre(){
        return $this->belongsToMany(Theatre::class,'city_movie_theatre');
    }
    public function city(){
        return $this->belongsToMany(City::class,'city_movie_theatre');
    }
}

Theatre Model

class Theatre extends Model
{
    use HasFactory;
    public function city(){
        return $this->belongsToMany(City::class,'city_movie_theatre');
    }
    public function movie(){
        return $this->belongsToMany(Movie::class,'city_movie_theatre','theatre_id','movie_id');
    }
}

Pivot Table Model

use Illuminate\Database\Eloquent\Relations\Pivot;
class City_Movie_Theatre extends Pivot
{
    use HasFactory;
    protected $table='city_movie_theatre';
    
}

In your threatre model, mention in city_id as pivot

class Theatre extends Model
{
    use HasFactory;
    
    ...

    public function movie(){
        return $this->belongsToMany(Movie::class,'city_movie_theatre','theatre_id','movie_id')->withPivot('city_id')->withTimestamps();
    }
}

Then put the where condition on your relation and on your pivot column

Theatre::whereHas('movie', function ($query) {
    return $query->where('movie_id', '=', 1);
})->wherePivot('city_id', '=', 1)->get();

If you want any dynamic value for movie_id then use use($movie_id) and put it in condition

$movie_id = $city_id = 1;
Theatre::whereHas('movie', function ($query) use($movie_id, $city_id){
    return $query->where('movie_id', '=', $movie_id);
})->wherePivot('city_id', '=', $city_id)->get();

You can use "relation" with a closure where you can define your matching condition.

Movie::with('theater', function($query) use ($theater_id, $city_id){
  $query->where('theater_id',$theater_id); 
  })->with('city', function($query) use ($city_id){
    $query->where('city_id',$city_id);})->get();

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