gpt4 book ai didi

mysql - 将数据库关系更改为 Laravel eloquent

转载 作者:行者123 更新时间:2023-11-29 11:07:36 24 4
gpt4 key购买 nike

我花了三天时间尝试将这种关系从 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“分页”,如下所示:

$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()

关于mysql - 将数据库关系更改为 Laravel eloquent,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41152699/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com