我們都知道通過Laravel中數(shù)據(jù)庫查詢出來的模型對(duì)象都是基于數(shù)據(jù)庫字段粪薛,今天給大家展示一個(gè) Laravel Eloquent ORM 模型特性-附加值不存在于數(shù)據(jù)表中。
舉個(gè)簡單的栗子蛾扇,一篇文章(posts表)對(duì)應(yīng)有很多評(píng)論(comments表),我們獲取文章的同時(shí)需要獲取評(píng)論數(shù)量魏滚。通常的做法就是根據(jù) ORM 的關(guān)聯(lián)關(guān)系镀首,獲取評(píng)論數(shù)量:$post->comments()->count() 。
-
要定義關(guān)聯(lián)關(guān)系鼠次。
class Post extends Model { /** * The attributes that are mass assignable. * * @var array */ protected $fillable = ['title', 'text']; /** * 文章對(duì)應(yīng)多條評(píng)論 * @return \Illuminate\Database\Eloquent\Relations\HasMany */ public function comments() { return $this->hasMany(Comment::class); } }
創(chuàng)建訪問器
public function getCountCommentsAttribute()
{
return $this->comments()->count();
}添加屬性
protected $appends = ['count_comments'];
這樣就大功告成了蘑斧。
如果獲取的是一個(gè)文章列表,那么最直接的辦法就是 froeach 查詢出來的文章须眷,然后每篇文章獲取評(píng)論數(shù)量竖瘾;另外一種做法就是用 with 然后在閉包里面實(shí)現(xiàn)評(píng)論數(shù)量。
$posts = App\Post::with(['comments' => function ($query) { $query->count(); }])->get();
轉(zhuǎn)載于:[https://laravel-china.org/topics/3521(https://laravel-china.org/topics/3521).`