将数据库关系更改为 Laravel eloquent
Changing a database relationship to Laravel eloquent
我尝试了三天将这种关系从 Laravel query_builder 转移到 Laravel eqloquent。但是看起来没用:
$category_products = DB::table('products')
->Join('categories', 'products.category_id', '=', 'categories.id')
->select('products.*', 'categories.CategoryEnName')
->where('categories.parent_id', '=', '2')
->get();
上面的代码运行良好,但不适用于 laravel "pagination",如下所示:
$category_products = DB::table('products')
->Join('categories', 'products.category_id', '=', 'categories.id')
->select('products.*', 'categories.CategoryEnName')
->where('categories.parent_id', '=', '2')
->get()->paginate(15);
这是我的类别模型:
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');
}
我想要的是如何将代码从查询生成器更改为 Laravel eloquent?
如果使用paginate()
,则不需要get()
我尝试了三天将这种关系从 Laravel query_builder 转移到 Laravel eqloquent。但是看起来没用:
$category_products = DB::table('products')
->Join('categories', 'products.category_id', '=', 'categories.id')
->select('products.*', 'categories.CategoryEnName')
->where('categories.parent_id', '=', '2')
->get();
上面的代码运行良好,但不适用于 laravel "pagination",如下所示:
$category_products = DB::table('products')
->Join('categories', 'products.category_id', '=', 'categories.id')
->select('products.*', 'categories.CategoryEnName')
->where('categories.parent_id', '=', '2')
->get()->paginate(15);
这是我的类别模型:
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');
}
我想要的是如何将代码从查询生成器更改为 Laravel eloquent?
如果使用paginate()
,则不需要get()