Php Laravel雄辩地从多个表中检索数据

Php Laravel雄辩地从多个表中检索数据,php,laravel,eloquent,laravel-5.1,Php,Laravel,Eloquent,Laravel 5.1,我有四张桌子 **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从数据库中获取与当前登录用户相关的最喜爱的

我有四张桌子

**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从数据库中获取与当前登录用户相关的最喜爱的文章列表(文章名称、所有者名称、类别名称)

是否可以在单行请求中执行此操作?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()

它看起来有点复杂,并且不使用雄辩的关系。

您可以利用laravel Earge loading,这也称为雄辩的关系

雄辩的关系定义为雄辩的模型类上的函数

文章中的模式

public function article()
{
    return $this->hasOne('App\Model\Category');
}
这样,您需要在相应的模型类中定义所有关系


有关更多信息:

完成@zippo_uuu回答,在
控制器中,您必须参考所需的表格,例如:

User.php

在例如UserController.php中

编辑:

如果要将用户与Article.Category关联,请在创建与用户和文章的关系之后

Article.php

e、 g.UserController.php


您只需在
用户
模型和
文章
模型之间设置一个参数即可。是的,我可以,但是如何从其他表(category_name value)获取数据@user947668我更新了我的答案,希望对您有所帮助。幸运的是,这个问题仍然没有得到回答。正如@Bogdan所建议的,我创建了多对多关系,但这种关系不允许我检索category_name值。
use Article;

public function article()
{
    return $this->hasOne('App\Article');
}
$user = User::with('article')->get();
use Category;

public function category()
{
    return $this->hasOne('App\Category');
}
$user_articles_categories = User::with('article.category')->get();