I would like to create a withCount subquery for this model.
Thanks to Iqbal Butt I have this snippet for getting the count.
$count = Action::select('article_id as assigned');
if (!empty($action_type_id))
{
$count = $count->where('action_type_id', $action_type_id);
}
if (!empty($set_id))
{
$count = $count->where('set_id', $set_id);
}
$count = $count->distinct('article_id')->count('article_id');
I would like to execute it like this, but I feel this is painfully flawed.
Clarification edit
I have a many to many relationship of sets to articles.
Each article has a number of actions.
The actions can have a variety of action types.
I need to count the types of actions for each article in a given set.
$sets = Set::withCount(['actions' => function ($q) use ($action_type_id, $set_id) {
$q->select('article_id as assigned');
if (!empty($action_type_id))
{
$q->where('action_type_id', $action_type_id);
}
if (!empty($set_id))
{
$q->where('set_id', $set_id);
}
$q->distinct('article_id')
->count('article_id');
// I believe this is executing inner query
}])
->get();
return $sets;
This gives me the error, more then likely because the inner query is executing and without the outer query.
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'sets.id' in 'where clause' (SQL: select count(distinct
article_id
) as aggregate fromactions
wheresets
.id
=actions
.set_id
andaction_type_id
= 1 andset_id
= 1)
Edit per comments
Article Model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Article extends Model
{
/**
* Get the sets for the article.
*/
public function sets()
{
return $this->belongsToMany(Set::class);
}
public function actions()
{
return $this->hasMany(Action::class);
}
}
Set Model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Set extends Model
{
/**
* Get the articles for the set.
*/
public function articles()
{
return $this->belongsToMany(Article::class);
}
public function actions()
{
return $this->hasMany(Action::class);
}
}
Action Model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Action extends Model
{
/**
* Get the set that owns the action.
*/
public function set()
{
return $this->belongsTo(Set::class);
}
/**
* Get the article that owns the action.
*/
public function article()
{
return $this->belongsTo(Article::class);
}
}
Database
actions
id
set_id
article_id
action_type_id
sets
id
name
articles
id
name
article_set
id
set_id
article_id