用户应该能够为多本书籍设置评分,这允许用户为仅一本书而不是其他书籍设置评分。
问题
用户无法对进行其他评分 另一本书。但是,另一个用户 可以对同一本书进行评分,但是不能对同一本书进行评分 其他书籍。即使用户注销也不会。
我正在使用rateYo和laravel-ratable
我的设置方式是,默认情况下将评级type
设置为false,从而使用户可以设置星星并进行相当大的评级。
再一次,一旦用户对任何书籍进行评分都没关系,则评分type
设置为true,将使用户无法设置星级。
这就是我拥有的
这是html设置的样子
HTML
<div id="rateYo" data-rateyo-rating="{{ $book->userSumRating or 0}}" data-rateyo-read-only="{{ $book->rated ? 'true' : 'false' }}"></div`>
BookController.php
public function rate(Request $request, $book_id)
{
$book = Book::find($book_id);
$rating = $book->ratings()->where('user_id', auth()->user()->id)->first();
if(is_null($rating)){
$ratings = new Rating();
$ratings->rating = $request['rating'];
$ratings->user_id = auth()->user()->id;
$ratings->type = Book::RATED;
$book->ratings()->save($ratings);
return json_encode($book);
}
else{
return response()->json(['status' => 'You already left a review']);
}
}
public function show($book_name)
{
$books = Book::GetBook($book_name)->get();
$data = $books->map(function(Book $book){
$book['rated'] = $book->type;
return $book;
});
return view('books.show', compact('data', $data));
}
Book.php (相关代码)默认情况下,如果未设置评分,则类型等于false,使用户能够进行评分;如果设置了评分,则类型等于真正禁用星标功能/阅读模式。
use Rateable;
const RATED = "true";
const NOT_RATED = "false";
protected $fillable = [ 'user_id', 'title', 'description'];
protected $appends = ['rated'];
public function getRatedAttribute()
{
return Rate::where('type', $this->owl() )->where('user_id', auth()->user()->id )->first();
}
public function owl(){
foreach($this->rate as $rates){
if ($rates->type != "true"){
return self::NOT_RATED;
}
}
return self::RATED;
}
public function rate()
{
return $this->hasMany('App\Rate', 'type', 'user_id');
}
答案 0 :(得分:1)
您需要在where子句中添加书籍ID,以检查用户是否对该特定书籍留下了评价。有了它,它将找到用户为任何图书留下的第一评价。
$constraints = [
'user_id' => auth()->id(),
'book_id' => $book_id
];
// checks if the user has not left a rating for this particular book
if ($book->ratings()->where($constraints)->doesntExist()) {
// create new rating...
} else {
// user has already rated this book...
}
答案 1 :(得分:0)
我需要将我的Book型号更改为以下型号,谢谢您数字化引导我朝着正确的方向
Book.php
public function getRatedAttribute()
{
$this->constraints = [
'user_id' => auth()->id()
];
if(Rating::where($this->constraints)->exists()){
return Rating::where(['type' => self::RATED, 'book_id' => $this->getKey()])->first();
}else{
return Rating::where('type' ,self::NOT_RATED)->first();
}
}