Laravel 5. Composite primary key. Unknown column 'id' in 'where clause'

不羁岁月 提交于 2020-04-18 06:04:31

问题


I don't use 'id' column in DB.
Instead, I use a composite primary key user_id + tmdb_id.
If I add new record like this:

$movie = new Movie();
$movie->user_id = 1;
$movie->tmdb_id = 2;
$movie->ratio = 3;
$movie->save();

it works fine!
But if I try to edit an existing record like this:

$movie = Movie::where([
            'user_id' => 1,
            'tmdb_id' => 2,
        ])->first();

$movie->ratio = 4;
$movie->save();

Then I have the error:

Unknown column 'id' in 'where clause'.

The migration file looks like this:

public function up()
{
    Schema::create('movies', function (Blueprint $table) {

        $table->integer('user_id')->unsigned();
        $table->integer('tmdb_id')->unsigned();
        $table->tinyInteger('ratio');

        // composite primary key
        $table->primary(['user_id', 'tmdb_id']);
    });
}

回答1:


Laravel doesn't support composite primary keys.

You have to use an additional package like https://github.com/mpociot/laravel-composite-key.




回答2:


Go to your Movie.php model and add this

protected $primaryKey = ['user_id', 'tmdb_id'];

The primary key is normally assumed to be id.



来源:https://stackoverflow.com/questions/49924862/laravel-5-composite-primary-key-unknown-column-id-in-where-clause

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!