简体   繁体   English

每个父母如何从模型中获取N条记录? 在laravel雄辩

[英]how to get N records from a model per parent ? In laravel eloquent

How can i get n records from a model per parent in laravel eloquent. 我如何从Laravel雄辩的每个父母的模型中获取n条记录。

For example lets say i have products table and categories table. 例如,假设我有products表和categories表。 And i want a list of all the products who's name starting with A but not more then 10 products per category . 我想要列出所有名称以A开头但每个category不超过10个产品的产品的列表。

My table structure is something like this. 我的表结构是这样的。

products table 产品表

---------------------------------
id  | title | slug | category_id
----------------------------------

Category table 分类表

--------------
id  | title |
--------------

I tried to follow this example which is exactly what i want https://softonsofa.com/tweaking-eloquent-relations-how-to-get-n-related-models-per-parent/ 我试图按照这个例子正是我想要的https://softonsofa.com/tweaking-eloquent-relations-how-to-get-n-related-models-per-parent/

But when i tried to query just like the example in the link after adding the scope in my product model . 但是,当我在product model添加范围后,尝试像链接中的示例一样查询时。 It throwing and sql error saying. 它抛出和SQL错误的说法。

SQLSTATE[HY000]: General error: 1267 Illegal mix of collations (utf8mb4_unicode_ci,IMPLICIT) and (utf8mb4_0900_ai_ci,IMPLICIT) for operation '=' (SQL: select count(*) as aggregate from... SQLSTATE [HY000]:常规错误:1267操作'='的排序规则(utf8mb4_unicode_ci,IMPLICIT)和(utf8mb4_0900_ai_ci,IMPLICIT)的非法混合(SQL:选择count(*)作为汇总,来自...

Can anyone please tell how i can get n results per related model or how can i fix this error. 任何人都可以告诉我如何从每个相关模型中获得n个结果,或者如何解决此错误。

Pass a query when you call relation: 调用关系时传递查询:

Category::with(['products' => function($query){
    $query->take(10)->skip(0);
}])->get();

Assuming you have a relation in your Category model. 假设您在“类别”模型中有一个关系。

public function products()...

First lets create your models: 首先让我们创建模型:

class Category extends Model
{
    public $timestamps = false;

    protected $fillable = [

       'title'];

    public function products(){
    return $this->hasMany(\App\Products::class)->limit(10);
}
}

and the second one: 第二个:

class Products extends Model
{
    public $timestamps = false;

    protected $casts = [
        'category_id' => 'int',
    ];

    protected $fillable = [

       'title',
        'slug'
    ];

    public function category()
    {
        return $this->belongsTo(\App\Category::class);
    }
}

Using eloquent the following would be: 用雄辩的话是:

$Category = Category::get();

You can also use starts_with() to define the column, word 您也可以使用starts_with()定义列,单词

From how I see it, for each categoryID you need an array of 10 products to be listed. 从我的角度来看,对于每个categoryID,您需要列出10个产品的数组。 Using Eloquent, this is what I came up with 使用Eloquent,这就是我想出的

$categories = Category::all()
productsArray = array();
foreach($categories as $category) {
        $products = Product::where('category_id', $category->id)->where('title', 'LIKE', 'A%')->get();
        if(sizeof($products)) {
            $products = $products->take(10);
            $productsArray[$category->id] = $products;
        }
    }
return $productsArray;

The only down side I see in this is the looping for each category ID, which might take more time if you have thousands of records. 我唯一看到的缺点是每个类别ID的循环,如果您有成千上万的记录,则可能需要更多时间。 You can have any other key, other than $category->id if you wish to show it in your blade file. 如果希望在刀片文件中显示,则可以使用$ category-> id以外的任何其他键。

There is no native support for this in Laravel. Laravel中对此没有本地支持。

I created a package for it: https://github.com/staudenmeir/eloquent-eager-limit 我为此创建了一个包: https : //github.com/staudenmeir/eloquent-eager-limit

Use the HasEagerLimit trait in both the parent and the related model. 在父模型和相关模型中都使用HasEagerLimit特征。

class Category extends Model {
    use \Staudenmeir\EloquentEagerLimit\HasEagerLimit;
}

class Product extends Model {
    use \Staudenmeir\EloquentEagerLimit\HasEagerLimit;
}

Then you can apply limit() / take() to your relationship: 然后,您可以将limit() / take()应用于您的关系:

Category::with(['products' => function($query) {
    $query->where('name', 'LIKE', 'A%')->limit(10);
}])->get();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Laravel Eloquent Relationship: How to get parent of parent information from child using Laravel eloquent model relationship? - Laravel Eloquent Relationship: How to get parent of parent information from child using Laravel eloquent model relationship? 调整雄辩的关系-每个父母如何获得N个相关模型? - Tweaking Eloquent relations – how to get N related models per parent? Laravel Eloquent/MySQL 如何从每个父记录的最后一个条目中获取去年的记录? - Laravel Eloquent/MySQL how to get one last year records from last entry of each parent record? 如何在Laravel中获取最新的n个相关模型记录 - How to get latest n number of related model records in laravel Laravel Eloquent从自引用表中获取N Level层次结构记录与其他表的列 - Laravel Eloquent get N Level hierarchy records from self-referencing table with other table's columns Laravel eloquent 模型如何从关系表中获取数据 - Laravel eloquent model how to get data from relationship's table 如何通过使用laravel 5 eloquent模型获得第三表基础上的第一个表记录 - How can i get First table records on base of third table by using laravel 5 eloquent model Laravel Eloquent - 如何使用 Eloquent 只获得每个父母的 2 个孩子? - Laravel Eloquent - how to get only 2 child of each parent using Eloquent? 获取由Laravel Eloquent中父模型中的字段筛选的相关列的SUM - Get SUM of a related column filtered by a field in the parent model in Laravel Eloquent 用雄辩的laravel从父模型中选择某些列 - selecting certain columns from parent model with Eloquent laravel
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM