【问题标题】:How to create two Foreign Key on pivot table linked to one Primary Key如何在链接到一个主键的数据透视表上创建两个外键
【发布时间】:2016-11-26 15:38:16
【问题描述】:

我正在尝试在需要插入保存当前登录用户的位置实现。将收件人插入 user_id 列效果很好,但我需要操作谁发送我需要获取用户ID的数据。我有两个表 usersdocuments 带有一个数据透视表 document_user

用户

 Schema::create('users', function (Blueprint $table) {
        $table->increments('id');
        $table->string('email');
        $table->string('username');
        $table->string('password');
        $table->string('remember_token');
 });

文档表格

Schema::create('documents', function (Blueprint $table) {
        $table->increments('id');
        $table->string('title');
        $table->text('content');
        $table->integer('category_id')->unsigned();
        $table->foreign('category_id')->references('id')->on('categories')->onDelete('cascade');
        $table->timestamps();
    });

document_user - 数据透视表

Schema::create('document_user',function (Blueprint $table)
    {
        $table->increments('id');
        $table->integer('user_id')->unsigned();
        $table->integer('document_id')->unsigned();

        $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
        $table->foreign('document_id')->references('id')->on('documents')->onDelete('cascade');
        $table->dateTime('dateReceived')->default(DB::raw('CURRENT_TIMESTAMP'));
    });

数据库设计:

注意!我只在 users 表迁移中插入几列,只是为了保存一行文本。

型号

用户

public function documents()
{
    return $this->belongsToMany('App\Models\Document', 'document_user', 'user_id', 'document_id');
}

文档

public function recipients()
{
    return $this->belongsToMany('App\Models\User', 'document_user', 'document_id', 'user_id');
}

根据用户对数据透视表的选择插入记录效果很好。但是当我尝试回滚我的迁移并将我的数据透视表更改为此时。

$table->integer('sender_id')->unsigned();
$table->foreign('sender_id')->references('id')->on('users')->onDelete('cascade');

我收到一条错误消息:

SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`webdev`.`document_user`, CONSTRAINT `document_user_sender_id_foreign` FOREIGN KEY (`sender_id`) REFERENCES `users` (`id`) ON DELETE CASCADE) (SQL: insert into `document_user` (`document_id`, `user_id`) values (34, 10))

如何实现在我的数据透视表中插入当前用户?所以我可以跟踪谁发送和接收数据。任何帮助将不胜感激!干杯!

更新 1:

感谢@Dastur 解决了我的问题。

document_user

Schema::create('document_user',function (Blueprint $table)
    {
        $table->increments('id');
        $table->integer('user_id')->unsigned();
        $table->integer('document_id')->unsigned();

        $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
        $table->foreign('document_id')->references('id')->on('documents')->onDelete('cascade');

        $table->unsignedInteger('sender_id')->nullable();
        $table->foreign('sender_id')->references('id')->on('users')->onDelete('cascade')->onUpdate('cascade');


        $table->dateTime('dateReceived')->default(DB::raw('CURRENT_TIMESTAMP'));
    });

我只是很难获得当前用户的 id 并将其插入sender_id 列。仍然没有任何想法,因为我需要跟踪用户创建的文档。

文档控制器

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Http\Requests;
use App\Models\Document;
use App\Models\User;
use DB;
use Auth;

class DocumentController extends Controller
{

public function getDocuments()
{
    //GETTING ALL THE ID OF THE USERS IN THE DATABASE EXCEPT THE ID OF CURRENT USER.
    $resultRecipient = DB::table('users')->where('id', '!=', Auth::id())->get();


    //GETTING ALL THE CATEGORIES.
    $resultCategory = DB::table('categories')->get();

    //VIEW
    return view ('document.create')->with('resultRecipient', $resultRecipient)->with('resultCategory', $resultCategory);
}

public function postDocuments(Request $request)
{

    $this->validate($request,
    [
        'title' => 'required|alpha_dash|max:255',
        'content' => 'required',
        'category_id' => 'required',
        'recipient_id' => 'required',
    ]);


    $document = new Document();
                                //Request in the form
    $document->title = $request->title;
    $document->content = $request->content;
    $document->category_id = $request->category_id;

    $document->save();
    $document->recipients()->sync($request->recipient_id, false);

    return redirect()->back();  
}

}

更新2:根据@Dastur,我需要为我的数据透视表创建另一个模型document_user

用户文档(模型)

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class UserDocument extends Model
{
protected $table = 'document_user';
}

【问题讨论】:

  • 迁移不会插入到您的表中。你可以使用播种!
  • @ClearBoth 我认为我不能使用播种,因为这取决于当前登录的用户。

标签: php laravel eloquent laravel-5.2 pivot-table


【解决方案1】:

我在网上查了一下,在 laracasts 上找到了这个帖子:http://laravel.io/forum/09-18-2014-foreign-key-not-saving-in-migration。此外,当您尝试从另一个表中获取空值并将其放入不可为空的行中时,通常会引发此错误。

编辑:

你在这里做的很奇怪,我仍然认为数据透视表不是一个聪明的选择。这正是我要做的:

迁移:

首先,我将创建我的用户迁移,非常简单:

Schema::create('users', function (Blueprint $table) {
    $table->increments('id');
    $table->string('email');
    $table->string('username');
    $table->string('password');
    $table->rememberToken();
});

接下来我将创建我的文档表:

Schema::create('documents', function(Blueprint $table) {
    $table->increments('id');
    $table->string('title');
    $table->text('content');
    $table->integer('category_id');
    $table->integer('user_id');
    $table->integer('sender_id');
    $table->dateTime('dateRecieved')->default(DB::raw('CURRENT_TIMESTAMP'));
    $table->timestamps();
});

型号:

在您的用户和类别模型中,您需要以下方法:

public function documents() {
    $this->hasMany(/* Path to your document model */);
}

最后,在您的文档模型中,您需要以下方法:

public function category() {
    $this->belongsTo(/* Path to your category model */);
}

public function user() {
    $this->belongsTo(/* Path to your user model */);
}

文档控制器

public function postDocuments(Request $request)
{

    $this->validate($request,
    [
        'title' => 'required|alpha_dash|max:255',
        'content' => 'required',
        'category_id' => 'required',
        'recipient_id' => 'required',
    ]);

    /*
     * This part not exactly sure what to do, because of I don't know what
     * know what the difference is between the sender and the user, please
     * elaborate.
     */

}

【讨论】:

  • 我创建了一个数据透视表,以便跟踪创建的文档。如果我将 PK users 表链接到我的 documents 表中的 FK 可以吗?只是想知道是谁创建了文档?
  • 我认为可能需要调用两行“sender_id”
  • 我要把这个“sender_id”添加到documents表中吗?因为我需要跟踪创建的文档,所以我创建了一个数据透视表。
  • 我详细阐述了我的答案。
  • 当我尝试将用户表中的 PK 引用到数据透视表中的 user_id 和 sender_id 时出现此错误。我正在尝试在我的数据透视表列中插入当前 id 用户 sender_id
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-04-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-30
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多