如何在 postman 中测试 laravel 模型关系

How to test laravel model relationship in postman

我正在尝试测试图书模型和评级模型之间的关系。只要用户在应用程序上登录,他们就应该能够对一本书进行评分。出于某种原因,我对邮递员 returns 的测试出现以下错误

SQLSTATE[HY000]: General error: 1364 Field 'rating' doesn't have a default value (SQL: insert into ratings (user_id, book_id, updated_at, created_at) values (2, 6, 2018-09-19 10:03:11, 2018-09-19 10:03:11))

这是我的评分模型

class Rating extends Model
{
protected $fillable = ['user_id', 'book_id', 'rating'];

/**
 * Rating/Book
 * A rating belongs to a book
 */
public function book()
{
    return $this->belongsTo(Book::class);
}
}

图书模型

class Book extends Model
{
protected $fillable = ['user_id', 'title', 'author'];

/**
 * Book/User relationship
 * A book belongs to only one user
 */
public function user()
{
    return $this->belongsTo(User::class);
}

/**
 * Book/Rating relationship
 * A book has many ratings
 */
public function ratings()
{
    return $this->hasMany(Rating::class);
}
}

评级控制器

public function store(Request $request, Book $book)
{
    // Allow only logged in users to rate books
    if ($request->user()->id) {

        $rating = Rating::create([
            'user_id'   => $request->user()->id,
            'book_id'   => $book->id,
        ],
        [
            'rating'    => $request->rating
        ]);

        return new Rating($rating);
    } else {
        return response()->json(['error', 'Login to rate this book.'], 403);
    }
}

我显然找不到问题出在哪里或如何解决它,需要一些专家的眼睛和指导。

您的 'rating' 值未提交。为什么评级在一个单独的数组中?您正在尝试创建一个对象以提交给数据库。我会尝试:

if ($request->user()->id) {

    $rating = Rating::create([
        'user_id'   => $request->user()->id,
        'book_id'   => $book->id,
        'rating'    => $request->rating
     ])

 ...

一个好的测试是在数据库中为评级创建一个默认值(例如 0),这样您就可以测试查询的哪些部分是成功的。

这是一个 sql 错误,与邮递员无关,在评级模型中,您有一个名为评级的列,当您在数据库中插入记录时,该列不能为空,您有两个解决方案,您可以设置当值为空时(例如 0 或 null 或空字符串和 ..),代码中评级列的值 其他解决方案是,您为数据库中的评级列设置默认值,例如 0 在迁移中:

 $table->integer('rating')->default(0)

或者说提交的数据库可以为空

$table->integer('rating')->nullable()
public function store(Request $request, Book $book)
{
    // Allow only logged in users to rate books
    if ($request->user()->id) {

        try {
            $rating = new Rating([
                'user_id'   => $request->user()->id,
                'book_id'   => $book->id,
                'rating'    => $request->rating
            ]);

            $rating->save();
            return $rating;
        } catch(Exception $ex) {
            return response()->json(['error', 'Failed to create new user'], 403);
        }
    } else {
        return response()->json(['error', 'Login to rate this book.'], 403);
    }
}