[英]Laravel - How to use a foreign key to a table with an identifying foreign key?
So I have three tables: users
, candidates
and logs
. 所以我有三个表:
users
, candidates
和logs
。 Now candidates
does not have its own id, it has an identifying foreign key user_id
. 现在
candidates
没有自己的id,它有一个识别外键user_id
。 Looking much like this: 看起来很像这样:
-users-
id
name
etc.
-candidates-
user_id
type
etc.
Now I want to have a table logs
that has a one-to-many relation with candidates
, being that a candidate can have zero or more logs
. 现在我希望有一个与
candidates
具有一对多关系的表logs
,即候选人可以拥有零个或多个logs
。 So I want to have a foreign key to candidates
, something like candidate_id
. 所以我想给
candidates
一个外键,比如candidate_id
。 However, putting it like this and Laravel won't automagically understand the relation. 但是,像这样,Laravel不会自动理解这种关系。 What should I name the foreign key from
logs
to candidates
to make Laravel understand the relationship? 我应该将
logs
从logs
命名为candidates
以使Laravel了解这种关系?
I think the simplest thing would be to give candidates its own incremental id and then have two relationship tables, candidate_user and candidate_log. 我认为最简单的方法是给候选人自己的增量id,然后有两个关系表,candidate_user和candidate_log。 It would be set up according to Laravel docs
它将根据Laravel文档设置
Your candidates table must have a primary key. 您的候选人表必须具有主键。
There's no need to have an incremental ID, but you shouldn't leave the table without a primary key. 不需要增量ID,但是不应该在没有主键的情况下离开表。
Once you define a primary key, you can use it as your reference. 定义主键后,可以将其用作参考。
Laravel will try to guess your foreign_key name: Laravel将尝试猜测您的foreign_key名称:
https://laravel.com/docs/5.2/eloquent-relationships#one-to-many https://laravel.com/docs/5.2/eloquent-relationships#one-to-many
Remember, Eloquent will automatically determine the proper foreign key column on the Comment model.
请记住,Eloquent将自动确定Comment模型上的正确外键列。 By convention, Eloquent will take the "snake case" name of the owning model and suffix it with _id.
按照惯例,Eloquent将采用拥有模型的“蛇案”名称,并以_id为后缀。 So, for this example, Eloquent will assume the foreign key on the Comment model is post_id.
因此,对于此示例,Eloquent将假定Comment模型上的外键是post_id。
If your primary key is not the "id" column, you should use the protected $primaryKey
and the public $incrementing
properties to describe your primary key in your Eloquent Model. 如果您的主键不是“id”列,则应使用
protected $primaryKey
和public $incrementing
属性来描述您的protected $primaryKey
模型中的主键。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.