如何在laravel-4中的三个模型之间建立关系?
问题描述:
我有以下数据结构:如何在laravel-4中的三个模型之间建立关系?
Table t:
(PK)id
order_id (this links to table or's id)
Table is:
(PK)id
tracking_id (this links to table or's tracking_id)
Table or:
(PK)id (this links to table t's order_id)
(FK)tracking_id
现在我的模型内(T.php)
我设置以下关系:
public function iS()
{
return $this->hasMany('is', 'tracking_id', 'order_id');
}
现在很明显,这并不因为工作tracking_id与order_id不匹配。
如何将这三个表连接在一起,以便我可以检索对应于t
表的is
数据?
我打电话是我这里面控制器:
$o = O::with('t', 't.iS')->where('id','=',$id)->first(); (O is my model for "o" table)
答
您正在寻找hasManyThrough关系。 http://laravel.com/docs/eloquent#has-many-through
在本文档例如:Country
具有Users
和Users
具有Posts
。 每个国家要获得职位定义:
class Country extends Eloquent {
public function posts()
{
return $this->hasManyThrough('Post', 'User', 'country_id', 'user_id');
}
}
在您的例子:T
有Or
和Or
具有Is
@neinI看到的例子,我试图做我T内所以它是这样的: 'return $ this-> hasManyThrough('或','Is')'没有正常工作。我是否在错误的模型中创建了关系? – 2014-09-04 07:14:49
您需要执行'$ this-> hasManyThrough('Is','Or');' – Nein 2014-09-04 07:25:06
另外,您需要手动指定关系键。 (因为默认的雄辩期望'or_id'和'is_id')。从文档示例中得出,我认为你需要做'$ this-> hasManyThrough('Is','Or','id','tracking_id');' – Nein 2014-09-04 07:33:47