Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
362 views
in Technique[技术] by (71.8m points)

laravel - Get records belonging to other records

I'm trying to get records belonging to other records. Here's a breakdown of the problem.

I have the following article records and would like to get the users who have articles with the status (0):

$articles = Article::whereStatus(0)->get();

The Article model looks like this:

<?php

namespace App;
use IlluminateDatabaseEloquentModel;

class Article extends Model
{
    protected $fillable = ['user_id', 'title', 'content', 'status'];

    public function user()
    {
        return $this->belongsTo('AppUser', 'user_id');
    }
}

I understand I can iterate through the articles records then fetch the respective user records but might this be inefficient? i.e.

foreach($articles as $article)
{
    $user = User::find($article->user_id);  
}

Is there an alternative method to get those users records with the articles?

question from:https://stackoverflow.com/questions/65848137/get-records-belonging-to-other-records

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can do this from the inverse direction:

User::whereHas('articles', fn ($q) => $q->whereStatus(0))->get();

Get all users that have any articles where status is 0.

You just need to have the articles relationship setup on User.

If you want all those User models to also have their articles relationship loaded with only Articles where status is 0, you can do a constrained eager load:

User::whereHas('articles', $filter = fn ($q) => $q->whereStatus(0))
    ->with('articles', $filter)
    ->get();

If you are starting with $articles you can lazy eager load the user relationship then pluck them from the Collection:

$articles->load('user')->pluck('user')->unique()

Laravel 8.x Docs - Eloquent - Relationships - Querying Relationship Existence whereHas

Laravel 8.x Docs - Eloquent - Relationships - Constraining Eager Loads with

Laravel 8.x Docs - Eloquent - Collections - Available Methods load

Laravel 8.x Docs - Eloquent - Collections - Available Methods unique

Laravel 8.x Docs - Collections - Available Methods pluck


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...