Yuval Kaufman
Yuval Kaufman

Reputation: 677

Laravel 5.2 Eloquent primary key as a multiple key

I have a model that has the following columns:

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!

Upvotes: 0

Views: 1320

Answers (1)

jedrzej.kurylo
jedrzej.kurylo

Reputation: 40909

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';
}

Upvotes: 0

Related Questions