php - 如何通过 laravel eloquent 模型连接三个表

标签 php mysql laravel

我有三张 table

文章表

 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 的方式来做。请问,我该怎么办?

最佳答案

使用 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');
        }
    }
  1. Category.php
    <?php
    namespace App\Models;
    
    use Eloquent;
    
    class Category extends Eloquent {
        protected $table = "categories";
    
        public function articles() {
            return $this->hasMany('App\Models\Article');
        }
    }
  1. 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 了解更多信息

关于php - 如何通过 laravel eloquent 模型连接三个表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29165410/

相关文章:

php - 用于 iphone 应用程序的 PHP 中的通知 cron

javascript - select2 显示不正确(使用 cdn)

php - 使用第一个脚本中的 "more info"按钮将数据拉入第二个脚本

php - 通过假设表 MySQL/PHP 中的列来设置值

laravel - 如何为没有子条目的父条目构建 Laravel Eloquent 查询?

javascript - 如何将 PHP 输入文本传递给 JavaScript 并返回给 PHP 标签

php - Laravel Dompdf 生成 pdf 报错

MySQL 行号是-58684。怎么可能?

mysql - Select, where 然后 inner join 两个表

linux - Laravel - 无法与主机 smtp.gmail.com 建立连接