Laravel Eloquent 从多个表中检索数据
Laravel Eloquent retrieve data from multiple tables
我有四张桌子
**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 从数据库中获取与当前登录用户相关的收藏文章列表(article_name、owner_name、category_name) ?
是否可以在单行请求中完成?例如:
$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()
看起来有点复杂,没有使用 eloquent 关系。
您可以利用 laravel 预先加载,也称为 Eloquent 关系。
Eloquent 关系在您的 Eloquent 模型 类 上被定义为函数 类。
例如。在文章模型中
public function article()
{
return $this->hasOne('App\Model\Category');
}
这样,您需要在各自的模型中定义所有的关系类。
完成@zippo_回答,在Controller
中你必须引用你想要的表格,例如
User.php
use Article;
public function article()
{
return $this->hasOne('App\Article');
}
例如UserController.php
$user = User::with('article')->get();
编辑:
如果要将用户与 Article.Category 关联,请在与用户和文章建立关联后
Article.php
use Category;
public function category()
{
return $this->hasOne('App\Category');
}
例如UserController.php
$user_articles_categories = User::with('article.category')->get();
我有四张桌子
**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 从数据库中获取与当前登录用户相关的收藏文章列表(article_name、owner_name、category_name) ?
是否可以在单行请求中完成?例如:
$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()
看起来有点复杂,没有使用 eloquent 关系。
您可以利用 laravel 预先加载,也称为 Eloquent 关系。
Eloquent 关系在您的 Eloquent 模型 类 上被定义为函数 类。
例如。在文章模型中
public function article()
{
return $this->hasOne('App\Model\Category');
}
这样,您需要在各自的模型中定义所有的关系类。
完成@zippo_回答,在Controller
中你必须引用你想要的表格,例如
User.php
use Article;
public function article()
{
return $this->hasOne('App\Article');
}
例如UserController.php
$user = User::with('article')->get();
编辑:
如果要将用户与 Article.Category 关联,请在与用户和文章建立关联后
Article.php
use Category;
public function category()
{
return $this->hasOne('App\Category');
}
例如UserController.php
$user_articles_categories = User::with('article.category')->get();