如何在laravel 5.4中根据子列明细对父数据进行排序?

wqsoz72f  于 2022-12-01  发布在  其他
关注(0)|答案(1)|浏览(109)

我有3路关系第一我有这样的代码在一个控制器

Trial::with('subjects')->where('source_id', $sourceId)->get()->toArray()

现在我想按subject.reactions.accounts.nb_followers列的降序对subject. reactions进行排序。我尝试在关系上使用orderby,但它不起作用,因为它按reactions对帐户indsted进行排序。我想根据帐户表中“nb_followes”列的值对reactions进行排序。
试验模型

class Trial extends Model
{
    use HasFactory;
    public $table = 'trials';

    public function subjects()
    {
        return $this->hasMany(Subject::class, 'trial_id')->with(['reactions', 'news'])->withCount('reactions');
    }
  }

主题模型

class Subject extends Model
{
    use HasFactory;
    public $table = 'subjects';

    public function reactions()
    {
        return $this->hasMany(Reaction::class, 'subject_id', 'id')->with(['accounts' => function ($q) {$q->orderBy('nb_followers', 'DESC');}])->where('twitter_error', 0)->where('active', 1)->orderby('key_reaction', 'DESC');
    }

    public function news()
    {
        return $this->hasone(News::class, 'id', 'news_item_id');
    }

React模型

class Reaction extends Model
{
    use HasFactory;

    public $table = 'reactions';

    public function accounts()
    {
        return $this->belongsTo(Account::class, 'account_id', 'id')->where('name', '!=', '');
    }

提前感谢您。

I want to sort reactions based on account table's column yes i cant use simple eloquent query because it will not create a structure that i want so that's why i created these relationships.
vsaztqbk

vsaztqbk1#

1.首先你需要使用Map方法遍历路径
1.第二,你需要使用转换方法来转换你的主题在排序的方式
1.如主题模型所示,您需要按key_reaction字段对React进行排序

$trails = ViewTrial::with('subjects')->where('source_id', $sourceId)->get();

$trails->map(function($trails){
        return $trails->subjects = $trails->subjects->transform(function (&$subject) {
           return [
                      "column" => $subject->column,
                      "reactions" => $subject->reactions->sortByDesc(function ($reactions) {
                                         return $reactions['accounts']['nb_followers'];
                                    })->sortByDesc('key_reaction')->values()->all()    
                   ]
                })->values();
            });

return $trails->toArray();

相关问题