ホーム > Laravel > How to Establish and Display Many-to-One Relationship in Laravel. Reverse of One-to-Many [belongsTo]
Laravel

How to Establish and Display Many-to-One Relationship in Laravel. Reverse of One-to-Many [belongsTo]

Thank you for your continued support.
This article contains advertisements that help fund our operations.

⇨ Click here for the table of contents of Laravel articles

I will write about how to establish and display a many-to-one relationship in Laravel.

Although you may not have seen the expression 'many-to-one' being used, I personally think that separating it makes it easier to understand at first, so I am writing separate articles on it.

The previous article on One-to-Many hasBeen there here

How to Establish and Display One-to-Many Relationship in Laravel [hasMany]

Basically, both this article and the previous one,

are summarized from the official documentation

Verification Environment

Laravel 6

Retrieving Related Data

This time, we will discuss how to retrieve data in the opposite direction from the previous article.

In the previous article, the direction was user⇨posts, but this time,

it will be posts⇨user (many-to-one)

Add to the model

Update the Post.php model.

class Post extends Model
{
    public function user()
    {
       return $this->belongsTo('App\User');
    }
}

We use an unfamiliar English term, 'belongsTo' (still not used to it)

For the controller,

use App\Post;

~~~~~~~~
    public function index()
    {
        $posts = Post::with('user')->get();
        //dd($posts);
        return view('home');
    }

That's it. Eager load with('function name defined in the model').

Display (views)

@foreach($posts as $post)
  {{ $post->title }}
  {{ $post->user->name }}
@endforeach

This way, you can easily display the title and username as a list.

Conclusion

What did you think?

The above is an article that I have summarized in an easy-to-understand way about relationships.

Basically, I think it's confusing to define belongsTo in articles where only one-to-many relationships are defined, but I deliberately separated them.

Hmm.

I wonder if I have not caused confusion by separating them. Once you get used to it, there shouldn't be any problems, but when I first started using Laravel a year and a half ago, I didn't understand many things, so I decided to separate them...

If you have any feedback or find any mistakes, please contact me via Twitter DM.

Related Articles

How to Establish and Display One-to-Many Relationship in Laravel [hasMany]

How to Establish a One-to-One Relationship in Laravel. [hasOne]

How to Establish and Display Many-to-Many Relationship in Laravel [belongsToMany]

Popular Articles

Deploying a PHP 7.4 + Laravel 6 Project to AWS EC2

Please Provide Feedback
We would appreciate your feedback on this article. Feel free to leave a comment on any relevant YouTube video or reach out through the contact form. Thank you!