Search code examples
mysqleloquentrelationshiplaravel-5.3

Changing a database relationship to Laravel eloquent


I'm trying for three days to transfer this relationship from Laravel query_builder to Laravel eqloquent. But it looks useless:

$category_products = DB::table('products')
            ->Join('categories', 'products.category_id', '=', 'categories.id')
            ->select('products.*', 'categories.CategoryEnName')
            ->where('categories.parent_id', '=', '2')
            ->get();

the code above is working well but it's not working with laravel "pagination" like this:

$category_products = DB::table('products')
                ->Join('categories', 'products.category_id', '=', 'categories.id')
                ->select('products.*', 'categories.CategoryEnName')
                ->where('categories.parent_id', '=', '2')
                ->get()->paginate(15);

That'smy category model:

class Category extends Model
{
    protected $guarded = ['id'];

    //For the nested "tree like" categories
    public function parent()
    {
        return $this->belongsTo('App\Category', 'parent_id');
    }

    //For the nested "tree like" categories
    public function children()
    {
        return $this->hasMany('App\Category', 'parent_id');
    }


    /**
    *
    *Grab all the products belong to this category
    *
    */
    public function products()
    {
        return $this->hasMany('App\Product');
    }

what I want is how I change the code from query builder to Laravel eloquent?


Solution

  • If you use paginate(), you don't need get()