Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
101 views
in Technique[技术] by (71.8m points)

php - how can we append two attributes by one function?

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Combining both methods to return an object is possible.

protected function getVariableNameAttribute()
{
    return DB::table("likes")
        ->selectRaw("SUM(liked) as likes")
        ->selectRaw("SUM(!liked) as dislikes")
        ->where('like_type', self::class)
        ->where('like_id', $this->id)
        ->first();
}
  • $...->variable_name->likes
  • $...->variable_name->dislikes

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...