【问题标题】:laravel withCount() Cardinality violation error when relationship is hasMany关系为hasMany时的laravel withCount()基数违规错误
【发布时间】:2022-01-01 07:48:19
【问题描述】:

这是我的模型:

//project model
class Project extends Model {
    .....
    public function items(){
        return $this->hasMany(ProjectItem::class,'project_id');
    }
}
//project items model
class ProjectItem extends Model{
    ...
 public function project(){
        return $this->belongsTo(Project::class);
    }
}

在我的控制器中,我想获取包含项目项计数的集合 $项目 =

Project::Select(['id','title'])->Where([            
            ['company' , '=', $company->id]
        ])->withCount('items')->paginate(50);

但我收到此错误:

SQLSTATE[21000]:基数违规:1242 子查询返回更多 超过 1 行 (SQL: select id, title, (select id from project_items 其中projects.id = project_items.project_id) 如items_count from projects where (company = 2) 限制 50 偏移 0)

这里有什么问题?为什么它在查询中不使用 SQL COUNT() 函数,而是仍然使用 SELECT?

我使用jetstream惯性,因此需要收集作为回报。而且我也不想在集合中加载关系模型。

编辑

这是我创建表格的方式:

//projects table
Schema::create('projects', function (Blueprint $table) {
            $table->id();
            $table->string('title');
            $table->unsignedBigInteger('company');
            $table->foreign('company')->references('id')->on('company')->onDelete('cascade');//projects is belong to another company table.
            $table->timestamps();
        });

//project_items table
Schema::create('project_items', function (Blueprint $table) {
            $table->id();
            $table->string('title');  
            $table->longText('desc')->nullable();
            $table->unsignedBigInteger('project_id');
            $table->foreign('project_id')->references('id')->on('projects');
            $table->timestamps();
        });

“项目”本身也属于“公司”表。但我认为不相关,因为我只在此处查询项目和项目项。

对不起,我的英语不好。

【问题讨论】:

    标签: eloquent laravel-8 laravel-controller laravel-models


    【解决方案1】:

    你能用这个替换你的查询并检查

    Project::select('id','title')->where('company' , $company->id)->withCount('items')->paginate(50);
    

    【讨论】:

    • 试过了,还是一样的错误
    • 尝试划分查询并检查它在哪个条件下出错。是withCount吗。
    • 是的,是 withCount 导致了错误。没有 withCount 也可以正常工作,即使 with() 也可以。
    • 我尝试生成相同但对我来说工作正常的东西。检查您的 withCount 是否适用于其他模型。如果不是,也许你使用的是旧的 mysql 版本。
    • 我尝试了其他型号,是的,它工作正常。我还用我用来创建表的迁移更新了这个问题。不确定它是否相关。谢谢
    猜你喜欢
    • 2019-11-12
    • 1970-01-01
    • 2016-10-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-04
    • 1970-01-01
    • 2018-05-18
    相关资源
    最近更新 更多