在查询模型Laravel中使用accesor getAttribute [英] Use accesor getAttribute in query model Laravel

查看:183
本文介绍了在查询模型Laravel中使用accesor getAttribute的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有Post模型,并且我有:

I have model Post, and I have:

protected $appends = ['reviews_count'];

public static function boot()
{
    parent::boot();

    static::saved(function () {
        static::updateRanks();
    });
}

public function reviews() {
   return $this->hasMany(Review:class);
}

public static function updateRanks()
{
    DB::statement("UPDATE posts set `rank` = (SELECT FIND_IN_SET( CONCAT(points, '_', created_at), (SELECT GROUP_CONCAT( CONCAT(points, '_', created_at) ORDER BY points desc, created_at asc ) FROM (select * from posts) as posts_rankings)))");
}

public function getReviewsCountAttribute()
{
    return $this->reviews()->active()->count();
}

我需要在CONCAT(points, '_', created_at)中添加一个reviews_count,然后执行ORDER BY points desc, reviews_count desc, created_at asc.我该怎么做?如果添加,则会出现错误:unknown column reviews_count...

I need in CONCAT(points, '_', created_at) add a reviews_count and next do ORDER BY points desc, reviews_count desc, created_at asc. How I can do this? If I add, I get error: unknown column reviews_count...

推荐答案

添加附加属性时,每次有雄辩的模式实例时laravel都会附加一种魔术属性.

When you add an appended property, it's a kind of magic property laravel appends each time you have an eloquent mode instance.

但是,您的表架构实际上没有reviews_count列.

But, your table schema dos not literally has reviews_count column.

如果您确实需要,可以使用join或subquery从SQL查询中获取该计数.但是,具有此类带有原始语句的更新功能并不是遵循的最佳实践.最终,它变得难以阅读和调试.我将建议您尽可能地组织它.不用担心,我们都去过那里:)

You can get that count from SQL query using join or subquery if thats what you really need. However, having such update functions with raw statements is not the best practice to follow. Eventually it becomes hard to read and debug. I will suggest you to structure it as well as you can. Don't worry, we all have been there :)

这篇关于在查询模型Laravel中使用accesor getAttribute的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆