Home > Database > Mysql Tutorial > body text

How to Join Three Tables in Laravel Using Eloquent?

Barbara Streisand
Release: 2024-11-12 21:21:02
Original
977 people have browsed it

How to Join Three Tables in Laravel Using Eloquent?

Joining Three Tables with Laravel Eloquent

Introduction

When working with relational databases, joining tables is often necessary to retrieve data across multiple tables. This article demonstrates how to join three tables in Laravel using the Eloquent ORM, offering an alternative to native SQL joins.

Database Schema

Consider the following database schema:

  • Articles table: id, title, body, category_id, user_id
  • Categories table: id, category_name
  • Users table: id, user_name, user_type

Querying with Eloquent

Relationship Setup

First, establish the relationships between the models:

// Article.php
class Article extends Eloquent {
    public function user() {
        return $this->belongsTo('App\Models\User');
    }

    public function category() {
        return $this->belongsTo('App\Models\Category');
    }
}

// Category.php
class Category extends Eloquent {
    public function articles() {
        return $this->hasMany('App\Models\Article');
    }
}

// User.php
class User extends Eloquent {
    public function articles() {
        return $this->hasMany('App\Models\Article');
    }
}
Copy after login

Join Query

To join the three tables and retrieve articles with their category and user details, use the with() method:

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

Accessing Related Data

Once the results are retrieved, you can access the related data as properties:

foreach ($articles as $article) {
    echo $article->title . ' - ';
    echo $article->user->user_name . ' - ';
    echo $article->category->category_name;
}
Copy after login

Conclusion

Using Eloquent to join tables simplifies and accelerates data retrieval in Laravel. By establishing relationships between models, you can easily access and manipulate related data.

The above is the detailed content of How to Join Three Tables in Laravel 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