سؤال

Consider the following query:

$tickets = Account::with('tickets')->where('name','LIKE',"%{$search}%")->paginate(10);

This is how I inverted it:

$tickets = Ticket::whereHas('account', function($q) use ($search)
{
    $q->where('name', 'LIKE', '%'. $search .'%');
})->paginate(10);

Is there another way to invert the first query?

I was looking for a way to execute the first query and receive only results from the tickets table. As it is now of course I will receive the tickets as a property of each account returned.

هل كانت مفيدة؟

المحلول

Answering your comment: yes, you can fetch tickets from 1st query. This is how to do it, though pagination is run in the context of accounts, so we will skip it and retrieve all the accounts:

// returns Eloquent Collection of Account models
$accounts = Account::with('tickets')->where('name','LIKE',"%{$search}%")->get();

// returns array of Ticket arrays (not models here)
$tickets = $accounts->fetch('tickets')->collapse();

As you can see it's possible but a bit cumbersome. Of course you can always prepare a helper method for this, but still you get arrays instead of models etc

So in fact I suggest using the 2nd solution, but here I'll give you something to make it nice and easy:

// Ticket model
public function scopeHasCategoryNameLike($query, $search)
{
  $query->whereHas('categories', function($q) use ($search) {
    $q->where('name', 'like', "%{$search}%");
  });
}

Then it's as simple as this:

$tickets = Ticket::hasCategoryNameLike($search)->paginate(10);
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top