我有四张桌子
**Articles table**
id
title
body
owner_id
category_id
**Favorite articles table**
id
user_id
article_id
**User table**
id
user_name
user_type
**Category table**
id
category_name
如何使用laravel eloquent从db获取与当前登录用户相关的收藏文章列表(article_name,owner_name,category_name)?
是否可以在单行请求中执行此操作? e.g:
$articles_data=Auth::user()->favorite_articles->article...
修改 目前我必须使用以下声明:
$articles_data = FavoriteArticle::where('user_id', Auth::id())->join('articles', 'articles.id', '=', 'favorite_articles.article.id')
->join('users', 'users.id', '=', 'favorite_articles.user_id')
->join('categories', 'categories.id', '=', 'articles.id')
->get()
这看起来有点复杂,并没有使用雄辩的关系。
答案 0 :(得分:3)
完成@zippo_回答,在"callout accessory control triggered!"
中你必须引用你想要的表格,例如。
user.php的
Controller
在例如 UserController.php
use Article;
public function article()
{
return $this->hasOne('App\Article');
}
编辑:
如果要在创建与用户和文章的关系
之后将User与Article.Category相关联Article.php
$user = User::with('article')->get();
e.g。 UserController.php
use Category;
public function category()
{
return $this->hasOne('App\Category');
}
答案 1 :(得分:1)
您可以利用laravel eager loading,这也称为Eloquent关系。
Eloquent关系被定义为Eloquent模型类的函数。
EG。在文章模型
public function article()
{
return $this->hasOne('App\Model\Category');
}
通过这种方式,您需要在各自的Model类中定义所有关系。