我有三张 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 中的场景。
我们有三种型号:
文章(属于用户和类别)
分类(有很多文章)
用户(有很多文章)
- 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');
}
}
- 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 中设置好关系后,检索相关信息就变得容易了。
例如,如果您想使用用户和类别检索文章,您需要编写:
$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/