I want to add two appends variables in laravel model. by using one getVariableNameAttribute() function.
Is this possible?
MY motto is, I want to reduce SQL query load 2 times to into 1 time
class Like extends Model{
use HasFactory;
protected $fillable = ['like_id', 'like_type', 'liked', 'user_id'];
protected $appends = ['likes','dislikes'];
protected function getLikesAttribute($type)
{
return DB::table("likes")
->select(DB::raw("SUM(liked) as likes"))
->where('like_type',self::class)->where('like_id',$this->id)->first()->likes;
}
public function getDislikesAttribute()
{
return DB::table("likes")
->select(DB::raw("SUM(!liked) as dislikes"))
->where('like_type',self::class)->where('like_id',$this->id)->first()->dislikes;
}}
question from:
https://stackoverflow.com/questions/65662219/how-can-we-append-two-attributes-by-one-function 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…