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

Categories

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

laravel - Getting entries from relationship and sub-relationship

I have three tables foo, bar and lorem. They are connected to each other with Many-To-Many relationships.

How can I efficiently get all entries of lorem where foo.id is 123, both directly and through bar (without duplicates) ?

=== EDIT ===

Schema:

Foo -> Lorem          |
                      |----- MERGE
Foo -> Bar -> Lorem   |

I'm currently doing it this way:

# Get lorems from foos
$loremsA = Foo::find(123)->lorems()->get();

# Get ids of bars for given foo:
$bar_ids = Foo::find(123)->bars()->pluck('id')->toArray();
# Get lorems from bars
$loremsB = Lorem::whereHas('bars', fn($q) => $q->whereIn('id', $bar_ids))->get();

# Merge
$loremsB->merge($loremsA)

Is there any better way to do it ?

question from:https://stackoverflow.com/questions/65903906/getting-entries-from-relationship-and-sub-relationship

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

1 Reply

0 votes
by (71.8m points)

Reverse-querying should work for you. Directly query the Lorem model, and check for reverse-relationship existence:

Lorem::whereHas('bars', function($query) {
  $query->whereHas('foos', function($subQuery) {
    $subQuery->where('foos.id', 123);
  })
})->get();

If Lorem can alternatively be directly related to Foo, then you can do an orWhereHas():

Lorem::whereHas('bars', function($query) {
  $query->whereHas('foos', function($subQuery) {
    $subQuery->where('foos.id', 123);
  })
})->orWhereHas('foos', function($query){ 
  $query->where('foos.id', 123);
})->get();

That should return all Lorem models that belong to a Bar that belongs to Foo, or that directly belongs to Foo.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...