你需要打电话
first
或
get
在访问器中的查询上:
return Rate::where(['type' => $this->getKey(), 'user_id' => auth()->id()])->first()
另外,在使用访问器时,不调用完整函数,如
getTypeAttribute
,只使用属性名,
type
.
// wrong
$book['rated'] = $book->getTypeAttribute();
// right
$book['rated'] = $book->type;
但是,我认为如果用户留下了评分,您应该使用
exists
或
doesntExist
查询函数。例如:
// this will return true/false
public function getRatedAttribute()
{
return Rate::where(['type' => $this->getKey(), 'user_id' => auth()->id()])->exists();
}
将属性附加到
Book
型号:
// this will add the attribute to each book in the query result.
protected $appends = ['rated']; // or type
然后您可以简单地使用:
$book->rated; // true if a rating exists, otherwise false.