我有3个表,其中一个是另外两个表之间的链接表。一个简单的多对多链接。
videos (Table fields shortened for brevity)
+----+---------------------+
| id | name |
+----+---------------------+
| 1 | test |
| 2 | Test Subscription 1 |
+----+---------------------+
subscriptions
+----+--------+
| id | name |
+----+--------+
| 1 | News |
| 2 | Sports |
| 3 | Gospel |
| 4 | Kids |
+----+--------+
subscription_video (link table between both models)
+----+-----------------+----------+
| id | subscription_id | video_id |
+----+-----------------+----------+
| 1 | 1 | 2 |
+----+-----------------+----------+
用于创建链接表的迁移
Schema::create('subscription_video', function(Blueprint $table)
{
$table->increments('id');
$table->integer('subscription_id')->unsigned();
$table->foreign('subscription_id')->references('id')->on('subscriptions');
$table->integer('video_id')->unsigned()->nullable();
$table->foreign('video_id')->references('id')->on('videos');
});
雄辩模式
class Video extends Model {
use SoftDeletes;
/**
* @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
*/
public function subscriptions()
{
return $this->belongsToMany('App\Subscription');
}
/**
* @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
*/
public function categories()
{
return $this->belongsToMany('App\Category');
}
}
现在根据文档,我应该能够通过调用
简单地检索结果Video::has('subscriptions')->get()
实际视图代码(有或没有orderBy时会发生相同的错误)
public function index()
{
$videos = Video::has('subscriptions')->orderBy('id', 'desc')->get();
return view('subscription.video.index', ['videos' => $videos ]);
}
在这种情况下应该使用video_id 2返回1个结果集。但无论我尝试什么,我都会继续
SQLSTATE[21000]: Cardinality violation: 1241 Operand should contain 9 column(s) (SQL: select `id`, `name` from `videos` where `videos`.`deleted_at` is null and (select * from `subscriptions` inner join `subscription_video` on `subscriptions`.`id` = `subscription_video`.`subscription_id` where `subscription_video`.`video_id` = `videos`.`id`) = 1)
我不知道我对这些关系的错误以及如何使Eloquent返回正确的结果?
任何帮助都将不胜感激。
1. in Connection.php line 620
2. at Connection->runQueryCallback('select * from
影片where
影片.
deleted_at is null and (select * from
订阅inner join
subscription_video on
订阅.
ID为=
subscription_video .
subscription_id where
subscription_video .
VIDEO_ID =
影片.
ID为) >= 1 order by
ID为desc', array(), object(Closure)) in Connection.php line 576
3. at Connection->run('select * from
影片where
视频{ {1}} deleted_at .
订阅is null and (select * from
subscription_video inner join
订阅on
ID为.
subscription_video =
subscription_id .
subscription_video {{1 }} VIDEO_ID where
影片.
ID为=
ID为.
影片) >= 1 order by
影片desc', array(), object(Closure)) in Connection.php line 293
4. at Connection->select('select * from
deleted_at where
订阅.
subscription_video is null and (select * from
订阅inner join
ID为on
subscription_video .
subscription_id =
subscription_video .
VIDEO_ID where
影片.
ID为{ {1}} ID为=