如何通过laravel eloquent模型连接三个表 [英] How to join three table by laravel eloquent model
问题描述
我有三张桌子
id
title
body
categories_id
user_id
类别表
id
category_name
用户表
id
user_name
user_type
我想显示带有类别名称而不是 category_id 和 user_name 而不是 user_id 的文章我试着像这些查询它是工作!
I want to show articles with their category name instead of category_id and user_name instead of user_id I try like these query It is work!
$articles =DB::table('articles')
->join('categories', 'articles.id', '=', 'categories.id')
->join('users', 'users.id', '=', 'articles.user_id')
->select('articles.id','articles.title','articles.body','users.username', 'category.name')
->get();
但我想通过 Eloquent 的方式来做.请问,我该怎么办?
But I want to do by Eloquent way. Please, how could I do?
推荐答案
使用 Eloquent 可以非常轻松地检索关系数据.请查看以下示例以及您在 Laravel 5 中的场景.
With Eloquent it's very easy to retrieve relational data. Check out the following example with your scenario in Laravel 5.
我们有三种模型:
文章(属于用户和类别)
Article (belongs to user and category)
类别(有很多文章)
用户(有很多文章)
- 文章.php
<?php
namespace App\Models;
use Eloquent;
class Article extends Eloquent {
protected $table = 'articles';
public function user() {
return $this->belongsTo('App\Models\User');
}
public function category() {
return $this->belongsTo('App\Models\Category');
}
}
- Category.php
<?php
namespace App\Models;
use Eloquent;
class Category extends Eloquent {
protected $table = "categories";
public function articles() {
return $this->hasMany('App\Models\Article');
}
}
- User.php
<?php
namespace App\Models;
use Eloquent;
class User extends Eloquent {
protected $table = 'users';
public function articles() {
return $this->hasMany('App\Models\Article');
}
}
您需要了解模型中的数据库关系和设置.用户有很多文章.该类别有很多文章.文章属于用户和类别.在 Laravel 中建立关系后,检索相关信息就变得容易了.
You need to understand your database relation and setup in models. The user has many articles. The category has many articles. Articles belong to user and category. Once you set up the relationships in Laravel, it becomes easy to retrieve the related information.
例如,如果要使用用户和类别检索文章,则需要编写:
For example, if you want to retrieve an article by using the user and category, you would need to write:
$article = \App\Models\Article::with(['user','category'])->first();
你可以这样使用它:
//retrieve user name
$article->user->user_name
//retrieve category name
$article->category->category_name
在另一种情况下,您可能需要检索某个类别中的所有文章或检索特定用户的所有文章.你可以这样写:
In another case, you might need to retrieve all the articles within a category or retrieve all of a specific user`s articles. You can write it like this:
$categories = \App\Models\Category::with('articles')->get();
$users = \App\Models\Category::with('users')->get();
您可以在 http://laravel.com/docs/5.0/eloquent 了解更多信息
You can learn more at http://laravel.com/docs/5.0/eloquent
这篇关于如何通过laravel eloquent模型连接三个表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!