0

这是我的模型:

//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);
    }
}

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

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

但我得到这个错误:

SQLSTATE[21000]:基数违规:1242 子查询返回多于 1 行(SQL:select id, title, (select idfrom project_itemswhere projects. id= project_items. project_id) as items_countfrom projectswhere ( company= 2) limit 50 offset 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();
        });

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

对不起,因为我的英语不好。

4

1 回答 1

0

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

Project::select('id','title')->where('company' , $company->id)->withCount('items')->paginate(50);
于 2022-01-01T08:00:02.887 回答