Home > Backend Development > PHP Tutorial > How to Define Composite Primary Keys in Laravel 5 Models?

How to Define Composite Primary Keys in Laravel 5 Models?

DDD
Release: 2024-12-03 20:40:12
Original
797 people have browsed it

How to Define Composite Primary Keys in Laravel 5 Models?

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)
}
Copy after login

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

    // ...
}
Copy after login

Additional Notes:

  • For Laravel versions 5.7 and up, you don't need to define the getIncrementing method in your trait.
  • If you encounter issues with Model::find, you can add the find method provided in the answer.
  • To use composite keys in conjunction with Eloquent's soft deleting functionality, you'll need to define the deletedAt and withTrashed methods.

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template