![](/img/trans.png)
[英]Can this query be handled using Laravel's Eloquent hasManyThrough() relationship or will a raw database query be required?
[英]Can I use Laravel's eloquent hasManyThrough relationship for my specific case?
我正在嘗試從與我當前使用的模型沒有直接關系的表中檢索數據。
我的數據結構:
表: 帖子
表: post_stacks
表: 堆棧
我雄辯的模型來自Post.php(posts表),而我正嘗試獲取與我的帖子相關聯的所有堆棧(來自stacks表)。 我只想在Post.php而不是我的數據透視表(post_stacks)上聲明我的關系。 我嘗試使用hasManyThrough,但無法正常工作嗎?
public function img()
{
return $this->hasManyThrough(\App\Stack::class, \App\PostStack::class, 'post_id', 'stack_id', 'id');
}
有誰知道我如何檢索我想要的數據? 謝謝!
您可以嘗試在帖子模型中放置以下關系嗎?
public function stacks()
{
return $this->hasManyThrough(
'App\Stacks', 'App\PostStacks',
'post_id', 'id', 'id'
);
}
也可以看看這個, https://laravel.com/docs/5.4/eloquent-relationships#has-many-through
根據該文檔, hasManyThrough
的第三個參數是中間模型上外鍵的名稱。 在我們的例子中, 'post_id'
是post_stack
上與posts
直接相關的外鍵。
第四個參數是最終模型上的外鍵名稱。 即,在stacks
上的'id'
。 與post_stacks
( 'post_id' )
有關系的。 第五個參數是本地密鑰。 即帖子id
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.