【发布时间】:2019-04-24 07:38:46
【问题描述】:
假设我有一个名为 Sportman 的模型和另一个名为 Sport 的模型通过 pivot 表链接:多对多关系。
他们的迁移示例代码。
# Sportmans migration
Schema::create('sportsmans', function (Blueprint $table) {
$table->increments('id');
$table->string('firstname');
$table->string('lastname');
});
# Sports migration
Schema::create('sports', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('description');
});
这是它们在模型中的关系:
# Defining association in Sportsman model
public function sports(){
return $this->belongsToMany( Sport::class, 'sportsman_has_sports', 'person_id', 'sport_id' );
}
# Defining association in Sports model
public function sportsman(){
return $this->belongsToMany( Sportsman::class );
}
如何使用 Laravel 和 Eloquent 获得 sportsman 播放:
- 仅限“足球”
- 盒子或“游泳”
- “网球和篮球
这是我尝试为问题 2 做的事情:
Sportsman::with(['sports:person_id,id,name'->whereHas('sports', function ($query) {
$query->whereIn('name', ['Box', 'Swimming'] );
});
最难的是第3题
【问题讨论】:
-
到目前为止你有什么尝试?
-
帖子是用我的方法编辑的,以回答您的问题
-
对于问题 2,您的方法有什么问题? “网球和篮球”是什么意思?
-
它有效,但正如我所说,问题 3 更难。我正在考虑的是在调用 @987654328 后以编程方式执行它(问题 3) @方法
-
既然已经有了解决方案,为什么还要问这个问题? “网球和篮球”是什么意思?
标签: php sql laravel laravel-5 eloquent