Home >Database >Mysql Tutorial >How to Retrieve Articles with Category and User Information using Eloquent?

How to Retrieve Articles with Category and User Information using Eloquent?

Patricia Arquette
Patricia ArquetteOriginal
2024-11-13 06:42:021031browse

How to Retrieve Articles with Category and User Information using Eloquent?

Eloquent Approach for Joining Three Tables

Problem:

Consider three tables: Articles, Categories, and Users. The objective is to retrieve Articles with their Category name and User name instead of their respective IDs.

Solution:

Eloquent offers a straightforward method to retrieve relational data.

Model Definition:

// Article.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
namespace App\Models;

use Eloquent;

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

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


// User.php
namespace App\Models;

use Eloquent;

class User extends Eloquent {
    protected $table = 'users';

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

Eloquent Query:

To retrieve Articles with Category and User information:

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

Usage:

To access the related data:

$article->user->user_name  //Retrieve user name
$article->category->category_name  //Retrieve Category name

Other Examples:

  • Retrieve all Articles within a Category:
$categories = \App\Models\Category::with('articles')->get();
  • Retrieve all Articles by a specific User:
$users = \App\Models\Category::with('users')->get();

Additional Resources:

  • Laravel Eloquent Documentation: http://laravel.com/docs/5.0/eloquent

The above is the detailed content of How to Retrieve Articles with Category and User Information using Eloquent?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn