This is my models:
//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);
}
}
In my controller I want to get the collection with the count of project items $projects =
Project::Select(['id','title'])->Where([
['company' , '=', $company->id]
])->withCount('items')->paginate(50);
But I get this error :
SQLSTATE[21000]: Cardinality violation: 1242 Subquery returns more than 1 row (SQL: select
id
,title
, (selectid
fromproject_items
whereprojects
.id
=project_items
.project_id
) asitems_count
fromprojects
where (company
= 2) limit 50 offset 0)
What is the problem here? Why it doesn't use the SQL COUNT() function in the query, but instead still using SELECT?
I using jetstream inertia , hence will need collection in return. And I also don't want to load the relationship model in the collections as well.
Edit
Here is how I create the tables:
//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();
});
The 'project' itself also belong to 'company' table. But I don't think is relevant since I only query the projects and the project items here .
Sorry because my bad English.