[英]How to perform a has-many-through-many-to-many eloquent relation in laravel 5.2?
[英]Laravel 5 Eloquent relation "Has Many Through" SQL Exception
你好。 昨天花了6个多小时搞懂了laravel 5中的ORM关系是如何工作的,但是我还不是很熟悉。
经过数百次错误、测试、研究等......我使我的一部分关系正常工作。
/* User.php (Model) */
public function lists() {
return $this->hasMany('App\ListModel');
}
public function tasks() {
return $this->hasManyThrough('App\Task', 'App\ListModel',
'user_id', 'list_id');
}
/* ListModel.php */
protected $table = 'lists';
public function user() {
return $this->belongsTo('\App\User', 'list_id');
}
public function tasks() {
return $this->hasMany('App\Task', 'list_id');
}
/* Task.php (Model) */
public function listModel() {
return $this->belongsTo('App\ListModel', 'list_id');
}
/* Returning all tasks (I have only one user yet. All tasks belongs to him) */
$request->user()->tasks()->get();
/* Working - Returning the list | lists */
$list = $request->user()->lists()->where('id', 'some-id')->first();
$lists = $request->user()->lists()->get();
/* Next line throws the SQL Exception */
$task = $request->user()->tasks()->where('id', '5')->first();
例外:
SQLSTATE[23000]:
Integrity constraint violation: 1052
Column 'id' in where clause is ambiguous
(SQL: select `tasks`.*, `lists`.`user_id` from `tasks`
inner join `lists` on `lists`.`id` = `tasks`.`list_id` where
`tasks`.`deleted_at` is null and `lists`.`deleted_at` is null
and `lists`.`user_id` = 1 and `id` = 5 limit 1)
/* The problem in where clause ^^^^^^^ */
laravel 生成的 SQL 查询不起作用。 我认为必须定义id
表。
注意: ListModel
类使用protected $table = 'lists'
。 List
词在 PHP (T_LIST) 中是原生的。 这个表名的变化让我感到恶心。 Laravel 关于“ORM 自定义键”的文档有点小。
谢谢你的时间。
问题实际上出在QueryBuilder
。
$request->user()->tasks()
返回QueryBuilder
我不确定它到底是如何工作的。 但我认为where()
函数添加了额外的 SQL。
我改变了这一行:
$task = $request->user()->tasks()->where('id', '5')->first();
到:
$task = $request->user()->tasks()->where('tasks.id', '5')->first();
其中, tasks
是数据库中的表, id
是列。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.