Я хотел бы создать подзапрос withCount для этой модели.
Благодаря Iqbal Butt У меня есть этот фрагмент для получения счета.
$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');
Я хотел бы выполнить это так, но я чувствую, что это болезненно испорчено,
Разъяснение правки
У меня есть много ко многим отношения наборов к статьям.
Каждая статья имеет несколько действий.
Действия могут иметь различные типы действий.
Мне нужно подсчитать типы действий для каждой статьи в данной статье.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;
Это дает мне ошибку, более вероятно, потому что внутренний запрос выполняется и без внешнего запроса.
SQLSTATE [42S22]: Столбецне найдено: 1054 Неизвестный столбец 'sets.id' в 'выражении where' (SQL: выберите количество (отличное article_id
) как совокупное значение из actions
, где sets
. id
= actions
. set_id
иaction_type_id
= 1 и set_id
= 1)
Редактировать по комментариям
Артикул Модель
<?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);
}
}
Установить модель
<?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);
}
}
Модель действия
<?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);
}
}
База данных
Действия
id
set_id
article_id
action_type_id
Наборы
id
name
артикулов
id
name
article_set
id
set_id
article_id