Laravel:如何在相关模型中添加复合键(2 列或更多列)作为 $primaryKey?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30427868/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Laravel: How to add a composite key (2 or more columns) as the $primaryKey in the related model?
提问by Amr
Name of the primary key column in any model in Laravel framework is id
Laravel 框架中任何模型的主键列的名称是 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?
我的问题是:如果我在表中有一个复合键(2 列或更多列),我该如何将它们添加为$primaryKey
? 我真的必须定义它们吗?
回答by Michael Lawton
From the Laravel docs:
来自Laravel 文档:
$table->primary(array('first', 'last'));
Edit: I misunderstood the question. This thread might provide some answers: http://forumsarchive.laravel.io/viewtopic.php?pid=34475
编辑:我误解了这个问题。这个线程可能会提供一些答案:http: //forumsarchive.laravel.io/viewtopic.php?pid=34475
Specifically overriding the find()
method.
具体覆盖该find()
方法。
public static function find($primaryOne, $PrimaryTwo) {
return Widget::where('primaryOne', '=', $primaryOne)
->where('PrimaryTwo', '=', $PrimaryTwo)
->first();
}