[英]Eloquent table relations
I am trying to pull a list of characters that belong to a certain user. 我试图提取属于某个用户的字符列表。 When I make the request I get an SQL Error.
当我发出请求时,出现SQL错误。 Reading through the error it is trying to us fields that don't exist.
通读错误,它试图向我们提供不存在的字段。
Error: 错误:
SQLSTATE[42000]: Syntax error or access violation: 1066 Not unique table/alias: 'characters' (SQL: select `characters`.*, `characters`.`id` as `pivot_id`,
`characters`.`character_id` as `pivot_character_id`
from `characters` inner join `characters` on `characters`.`id` = `characters`.`character_id` where `characters`.`id` = 1)
"character_id" does not exist in my database. 我的数据库中不存在“ character_id”。 The problem is I can't find where Eloquent is making that field.
问题是我找不到Eloquent在哪里制作该字段。 I looked through the source code and there was a lot of "If this is not provided use
$variable.'_id'
. I could not find that code anywhere for this though. 我仔细查看了源代码,发现有很多“如果未提供,请使用
$variable.'_id'
。 $variable.'_id'
我在任何地方都找不到该代码。
Models are below. 型号如下。
class Character extends Eloquent {
protected $guarded = array('id');
protected $table = 'characters';
public function User ()
{
return $this->belongsTo('User', 'id');
}
}
class User extends Eloquent implements UserInterface, RemindableInterface {
use UserTrait, RemindableTrait;
protected $table = 'users';
protected $hidden = ['password', 'remember_token'];
protected $guarded = ['password'];
public function Character ()
{
return $this->belongsToMany('Character', 'characters', 'id');
}
}
There is a foreign key between user_id
in the characters table, and id
in the users table. 字符表中的
user_id
和用户表中的id
之间有一个外键。
belongsToMany is for many-to-many relations . EmiratesToMany是用于多对多关系的 。 Laravel throws you an error because it expects third table - pivot table - containing both character_id and user_id.
Laravel向您抛出错误,因为它期望第三个表(数据透视表)同时包含character_id和user_id。
If you dont want many-to-many but one-to-many then you should use hasMany and belongsTo. 如果您不希望多对多,而是一对多 ,则应使用hasMany和belongsTo。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.