Home > Database > Mysql Tutorial > body text

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

Patricia Arquette
Release: 2024-11-13 06:42:02
Original
969 people have browsed it

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');
    }
}
Copy after login

Eloquent Query:

To retrieve Articles with Category and User information:

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

Usage:

To access the related data:

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

Other Examples:

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

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template