简体   繁体   中英

Laravel 5.2 Eloquent primary key as a multiple key

I have a model that has the following columns:

  • blog_id (fillabale)
  • date (fillable)
  • counter

Unique key on blog_id + date

whenever I'm trying to get results from this table by using, for instance,

$model = BlogCounter::findOrNew(2,'2016-09-25');

Or

$model = BlogCounter::whereBlogId(2)->whereDate('date','=','2016-09-25')->first()

I'm getting error:

column blog_counter.id does not exist

I tried to override primaryKey and set it to null / ['blog_id', 'date'] / 'blog_id,date' none of the above solved this problem of Eloquent trying to fetch raw by id..

I don't have primary key on this table because I'm using unique key instead.

Am I missing something? How do I enforce Eloquent models to work without a primary key?

BTY, I'm using PostgreSQL 9.5 at this point.

Thanks!

Eloquent assumes that there is an id column in your table that identifies a row. In your case this column is named blog_id so you need to let Eloquent know.

You can do that by defining primaryKey attribute in your model. It doesn't need to be the primary key in the database as long as it can be used to fetch a single record:

class BlogCounter extends Model {
  protected $primaryKey = 'blog_id';
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM