Home > Back-end >  Laravel simplify query method
Laravel simplify query method

Time:11-28

In Book model I have 2 methods

1 for get book list another for get auth user Favourites book list. Two methods like below

For get book list :

public function getBooks($id = null)
{
    $query = $this::with("bookImages","author","category")->withCount(['favourites'])->orderBy('created_at', 'desc');
    return $id ? $query->findOrFail($id):$query;
}

For get user fav book list

public function getFavList()
{
        return $this::join('favorites', function($query){
                $query->on('books.id','=','favorites.book_id')->where('favorites.user_id', '=', 1);
            })
            ->with("bookImages","author","category")->withCount(['favourites'])->orderBy('created_at', 'desc')
        ;
}

In both query with is common. So I'm trying to reuse getBooks method in getFavList method like below

public function getFavList()
{
        return $this::join('favorites', function($query){
                $query->on('books.id','=','favorites.book_id')->where('favorites.user_id', '=', 1);
            })
            ::$this->getBooks()
        ;
}

Here I'm getting Access to undeclared static property Illuminate\Database\Eloquent\Builder::$this. How can I simplify this method ?

CodePudding user response:

It's in the official documentation under "Eager Loading" Multiple relationships:

$books = Book::with('author', 'publisher')->get();

Nested relationships:

$books = Book::with('author.contacts')->get();

So for you:

Advert::with('getBooks.getFavList')->find(1);

Another way - You can even try the union method:

public function getFavBooks()
{
    return $this->getBooks()->union($this->getFavList()->toBase());
}

CodePudding user response:

Simple way is :P

return $this->getBooks()->join('favorites',function($query){
    $query->on('books.id','=','favorites.book_id')->where('favorites.user_id', '=', 1);
});
  • Related