繁体   English   中英

具有两个以上外来 ID 的数据透视表

[英]Pivot table with more than two foreign ids

所以我有一张桌子,城市

城市表

第二张桌子是电影

在此处输入图像描述

第三张桌子是剧院

在此处输入图像描述

我有一个连接所有这三个的数据透视表。

在此处输入图像描述

我想要实现的是,只获得city_idmovie_id具有特定值的那些影院。 这是我的控制器

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

我想要所有movie_id=1city_id=1的影院

电影模特

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');
    }
}

剧院模型

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');
    }
}

数据透视表模型

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

在您的威胁模型中,在 city_id 中提及作为枢轴

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();
    }
}

然后将 where 条件放在您的关系和数据透视列上

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

如果您想要 movie_id 的任何动态值,请使用use($movie_id)并将其置于条件

$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();

您可以将“关系”与闭包一起使用,您可以在其中定义匹配条件。

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();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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