Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 681
Amr Avatar asked May 24 '15 20:05

Amr


1 Answers

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();
} 
like image 183
Michael Lawton Avatar answered Oct 12 '22 16:10

Michael Lawton