对于一对一关系的情况,如果我在方法调用中完全指定key,hasOne
有区别吗?和 belongsTo
关系?或者,如果我使用 hasOne
,换一种方式问在关系的双方,结果会一样吗?
最佳答案
是的,它在某些情况下可以指定键并使关系起作用。在某些情况下,我的意思主要是 检索结果。下面是一个例子:
D B
users profiles
----- --------
id id
etc... user_id
etc...
楷模
与
hasOne
使用“错误”关系两次class User extends Eloquent {
public function profile(){
return $this->hasOne('Profile');
}
}
class Profile extends Eloquent {
public function user(){
return $this->hasOne('User', 'id', 'user_id');
}
}
查询
假设我们想从某个配置文件中获取用户
$profile = Profile::find(1);
$user = $profile->user;
这是有效的。但它并没有像它应该的那样工作。它将处理
users
的主键就像一个引用 user_id
的外键在 profiles
.虽然这可能有效,但在使用更复杂的关系方法时会遇到麻烦。
例如
associate
:$user = User::find(1);
$profile = Profile::find(2);
$profile->user()->associate($user);
$profile->save();
该调用将抛出异常,因为
HasOne
没有方法associate
. ( BelongsTo
有)结论
而
belongsTo
和 hasOne
在某些情况下可能表现相似。他们显然不是。与关系的更复杂的交互将不起作用,从语义的角度来看这是无稽之谈。
关于laravel - 如果同时指定了两个键,Eloquent hasOne 与belongsTo 会退化为相同的函数吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26150925/