Laravel Eloquent 从多个表中检索数据

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32923775/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 12:26:34  来源:igfitidea点击:

Laravel Eloquent retrieve data from multiple tables

phplaraveleloquentlaravel-5.1

提问by user947668

I have four 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

How to get list of favorite articles (article_name,owner_name,category_name) which related to currently logged user from db using laravel eloquent?

如何使用laravel eloquent从数据库中获取与当前登录用户相关的最喜欢的文章列表(文章名称、所有者名称、类别名称)?

Is it possible to do it in single line request? e.g.:

是否可以在单行请求中做到这一点?例如:

$articles_data=Auth::user()->favorite_articles->article...

EDITFor the moment i have to use statement below:

编辑目前我必须使用以下语句:

$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()

Which looks a bit complicated and doesn't use eloquent relations.

这看起来有点复杂,没有使用雄辩的关系。

采纳答案by AndreL

Completing @zippo_ answer, in the Controlleryou must reference what tables you want, e.g.

完成@zippo_ 回答,在Controller你必须引用你想要的表中,例如

User.php

用户名.php

use Article;

public function article()
{
    return $this->hasOne('App\Article');
}

and in the e.g. UserController.php

并在例如UserController.php

$user = User::with('article')->get();

EDIT:

编辑:

if you want to relate User to Article.Category, after create a relation with user and article

如果您想将 User 与 Article.Category 相关联,则在创建与用户和文章的关系后

Article.php

文章.php

use Category;

public function category()
{
    return $this->hasOne('App\Category');
}

e.g. UserController.php

例如UserController.php

$user_articles_categories = User::with('article.category')->get();

回答by rajangupta

You can take advantage of laravel eager loading, which are also called as Eloquent relationships.

您可以利用 laravel 的预先加载,也称为 Eloquent 关系。

Eloquent relationships are defined as functions on your Eloquent model classes.

Eloquent 关系被定义为 Eloquent 模型类上的函数。

Eg. In Article Model

例如。文章模型

public function article()
{
    return $this->hasOne('App\Model\Category');
}

In this way, you need to define all the relationships in the respective Model classes.

这样,您需要在各自的 Model 类中定义所有关系。

for more info: http://laravel.com/docs/5.1/eloquent-relationships

更多信息:http: //laravel.com/docs/5.1/eloquent-relationships