让我有 3 个表,分别命名为 user
、admin
、post
我的帖子表结构是
-id
-poster_id
-poster_type //if value is 1 then poster_id will be releted with user table. if value is 2 then poster_id releted with admin table.
现在如何根据海报类型值编写与两个表的belongsTo
关系
我想在 Post 模型中这样做
public function Author(){
return $this->belongsTo('User', 'poster_id')->where('poster_type', '1') //poster_type is the field of post table.
}
最佳答案
首先,你说的是多态关系,由 eloquent 支持。您应该查看文档。
http://laravel.com/docs/eloquent#polymorphic-relations
其次,您将 Eloquent 关系与特殊的数据恢复功能混合在一起,这是您应该避免的。我建议您将关系本身从数据恢复功能中分离出来。
此外,如果您想更进一步,请将关系保留在模型中,并将数据恢复功能拆分到存储库对象中。
关于laravel - laravel Eloquent 中的条件关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25956570/