首页 > 解决方案 > laravel 中的 3 列引用同一个表

问题描述

我正在将一个项目与一个仅基于应用程序的电子邮件系统放在一起。尝试做一些我不能 100% 确定可以完成但不知道解决方法的事情。基本上,有没有办法让一个表中的 3 列从数据库中其他位置的同一个表中提取数据?IE:

public function up()
{
    Schema::create('email', function (Blueprint $table) {
        $table->increments('id');
        $table->string('title');
        $table->text('body');
        $table->string('user_id'); //for the 'to' field column
        $table->string('user_id'); //for the 'from' field column
        $table->string('user_id'); //for the 'Cc' field column
        $table->timestamps();
    });
}

希望我的解释是有道理的。显然,user_id 引用了 users 表

标签: laravelmigration

解决方案


最好的方法是给每一列一个唯一的名字:

public function up()
{
    Schema::create('email', function (Blueprint $table) {
        $table->increments('id');
        $table->string('title');
        $table->text('body');
        $table->string('user_to_id'); //for the 'to' field column
        $table->string('user_from_id'); //for the 'from' field column
        $table->string('user_cc_id'); //for the 'Cc' field column
        $table->timestamps();
    });
}

然后在您的 EmailController.php 中,当您创建新电子邮件时,您将使用以下内容:

public function store() 
{
    $email = new Email; // Email model
    $email->user_to_id = $request->recipient_input
    $email->user_from_id = $request->cc_input
    $email->user_cc_id = Auth::user()->id; // Guessing that the from id is from a logged in person
    $email->title = $request->title;
    $email->body = $request->body;
    $email->save();
}

类似的东西:)


推荐阅读