如何通过laravel eloquent模型加入三个表

问题描述 投票:54回答:2

我有三张桌子

表项目

 id
 title
 body
 categories_id
 user_id

分类表

  id
  category_name

用户表

 id
 user_name
 user_type

我想用他们的类别名称而不是category_id和user_name而不是user_id来显示文章我尝试这些查询这是工作!

$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的方式做。拜托,我该怎么办?

php mysql laravel
2个回答
95
投票

使用Eloquent非常容易检索关系数据。使用Laravel 5中的方案查看以下示例。

我们有三种型号:

1)文章(属于用户和类别)

2)类别(有很多文章)

3)用户(有很多文章)


1)Article.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');
    }

}

2)Category.php

<?php

namespace App\Models;

use Eloquent;

class Category extends Eloquent
{
    protected $table = "categories";

    public function articles()
    {
        return $this->hasMany('App\Models\Article');
    }

}

3)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中设置关系后,可以轻松检索相关信息。

例如,如果要使用用户和类别检索文章,则需要编写:

$article = \App\Models\Article::with(['user','category'])->first();

你可以像这样使用它:

//retrieve user name 
$article->user->user_name  

//retrieve category name 
$article->category->category_name

在另一种情况下,您可能需要检索某个类别中的所有文章,或检索所有特定用户的文章。你可以像这样写:

$categories = \App\Models\Category::with('articles')->get();

$users = \App\Models\Category::with('users')->get();

您可以在http://laravel.com/docs/5.0/eloquent了解更多信息


16
投票

尝试:

$articles = DB::table('articles')
            ->select('articles.id as articles_id', ..... )
            ->join('categories', 'articles.categories_id', '=', 'categories.id')
            ->join('users', 'articles.user_id', '=', 'user.id')

            ->get();
© www.soinside.com 2019 - 2024. All rights reserved.