Defining Composite Primary Keys in Laravel 5 Models
You have a table with two primary keys (id and language_id) and want to include them in your Laravel 5 models. By default, the primary key in Laravel models is "id," but you need your primary keys to be "id" and "id_language."
To accomplish this, you can utilize a PHP trait that adapts Eloquent to handle composite keys:
namespace App\Model\Traits; // Adjust this to match your model namespace! use Illuminate\Database\Eloquent\Builder; trait HasCompositePrimaryKey { // ... (Code from provided answer) }
Place this trait in a "Traits" directory under your main model directory. Then, add the following line to the top of any composite-key model:
class MyModel extends Eloquent { use Traits\HasCompositePrimaryKey; // *** THIS!!! *** /** * The primary key of the table. * * @var string */ protected $primaryKey = array('key1', 'key2'); // ... }
Additional Notes:
The above is the detailed content of How to Define Composite Primary Keys in Laravel 5 Models?. For more information, please follow other related articles on the PHP Chinese website!