Amr
Amr

Reputation: 5159

Laravel: How to add a composite key (2 or more columns) as the $primaryKey in the related model?

Name of the primary key column in any model in Laravel framework is id

protected $primaryKey = 'id';

And I know I can change that default name like this:

protected $primaryKey = 'new_name';

My question is: What if I have a composite key (2 or more columns) in the table, how do I add them as the $primaryKey? And do I really have to define them?

Upvotes: 13

Views: 9625

Answers (1)

Michael Lawton
Michael Lawton

Reputation: 1510

From the Laravel docs:

$table->primary(array('first', 'last'));

Edit: I misunderstood the question. This thread might provide some answers: http://forumsarchive.laravel.io/viewtopic.php?pid=34475

Specifically overriding the find() method.

public static function find($primaryOne, $PrimaryTwo) {
    return Widget::where('primaryOne', '=', $primaryOne)
        ->where('PrimaryTwo', '=', $PrimaryTwo)
        ->first();
} 

Upvotes: 8

Related Questions