【问题标题】:Laravel 5.2 - set Primary key to email instead of 'id'Laravel 5.2 - 将主键设置为电子邮件而不是“id”
【发布时间】:2016-05-30 13:14:12
【问题描述】:
Schema::create('users', function (Blueprint $table) {<br>
            $table->primary('email');<br>
            $table->string('name');<br>
            $table->string('image_url');<br>
            $table->string('signin_with');<br>
        });

上面是我的数据库架构。

这是我的用户模型

<?php
namespace App;

use Illuminate\Database\Eloquent\Model;

class Users extends Model
{

    protected $table = 'users';
    public $incrementing = false;
    protected $primaryKey = 'email';

    protected $fillable = [
        'email', 'name' ,'image_url', 'signin_with'
    ];
} 

现在我的问题是我想将“电子邮件”属性作为用户表中的主键。但我得到一个错误

QueryException SQLState[42S01]。

我该如何解决?

提前谢谢你。

【问题讨论】:

  • 您可能不想将电子邮件设置为primary key。很可能您希望将其设置为unique 并添加index,因为主键也用于增量目的。
  • 我可能是错的,但 SQLState[42S01] 向我建议该表已经存在。你能发布完整的错误信息吗?
  • 我不希望电子邮件 ID 为空,因为我可以将其分配给 unique,那么它将只是该表中的一个电子邮件条目,但我不希望它也可以为空'不想。我需要其他表中的电子邮件 ID 为 foreign keycomposite key 。错误是 [Illuminate\Database\QueryException] SQLSTATE[42S01]: Base table or view already exists: 1050

标签: javascript php ajax laravel laravel-5.2


【解决方案1】:

主键用于链接其他表,字符串比较比int比较慢。

如果您将用户信息存储在多个表中,则用户表的外键将是电子邮件地址。

这意味着您多次存储电子邮件地址。 因此,不要使用电子邮件作为主键,而是使用自动递增的主键。

【讨论】:

  • 是的。我将电子邮件存储在表中,因为电子邮件 ID 将在其他表中使用,并且根据我们的要求,电子邮件 ID 应该是主键。那我该如何解决呢?
【解决方案2】:

在您的用户架构中:

$table->increments('id');
$table->string('email')->unique();

在需要用户的模型中

$table->integer('user_id')->unsigned();
$table->foreign('user_id')->references('id')->on('users');

您将在索引字段上有一个外键。无需在用户表的此字段上设置主键。

基于https://laravel.com/docs/5.2/migrations#creating-indexes

【讨论】:

    猜你喜欢
    • 2021-05-12
    • 2019-08-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-03
    • 2016-12-11
    • 2015-05-12
    相关资源
    最近更新 更多