【问题标题】:Can I create custom pivot table name using another M:M entity?我可以使用另一个 M:M 实体创建自定义数据透视表名称吗?
【发布时间】:2016-08-01 01:20:45
【问题描述】:

我仍在思考是否有办法创建自定义数据透视表名称?因为我创建了一个 documents 和 users 表与 document_user 这是我的 pivot table 和该表是为用户创建的已接收文档创建的。我计划为 document 和 user 创建另一个数据透视表,此表用于发送的文档,以便我可以了解历史记录。请参阅下面的代码。

create_document_user_table

public function up()
 {
    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');

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

documents_table

public function up()
{
    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();
    });
}

users_table

public function up()
{
    Schema::create('users', function (Blueprint $table) {
        $table->increments('id');
        $table->string('first_name');
        $table->string('last_name');
        $table->string('middle_name');
        $table->string('email');
        $table->string('username');
        $table->string('address');
        $table->string('password');
        $table->string('remember_token');

        $table->integer('role_permission_id')->unsigned();

        $table->foreign('role_permission_id')->references('id')->on('roles_permissions_dt')->onDelete('cascade');
        $table->timestamps();
    });
}

这很好地将记录插入我的数据透视表。我打算实现的是每次我为 documents 插入记录时,这也会插入到我的自定义数据透视表中,而不仅仅是在我的 document_user 数据透视表中。任何帮助将不胜感激!感谢您的信息或提示。

更新

@Mina 感谢您提供的提示,但实际上这是我的插入或保存我的数据透视表。如何将它插入到我的修订表中?

文档控制器

public function postDocuments(Request $request)
{

    $this->validate($request,
    [
        'title' => 'required|regex:/(^[A-Za-z0-9 ]+$)+/|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();
    $user = Auth::user();

    foreach($request->recipient_id as $recipientId)
    {
        $document->recipients()->sync([ $recipientId => ['sender_id' => $user->id]],false );
    }

    return redirect()->back();  
}

【问题讨论】:

  • 为什么是另一个数据透视表,它是直接与文档的关系。
  • @MinaAbadir 因为我所做的我需要为每个用户创建和接收文档的历史记录。这就是我创建 M:M 关系的原因。
  • 一个文档可以被多个用户创建吗?
  • @PaulSpiegel 是的,它可以由许多用户创建。

标签: php laravel laravel-5.2


【解决方案1】:

您可以随意调用数据透视表。

如前所述,确定表名 关系的连接表,Eloquent 会连接两个相关的模型 按字母顺序排列的名称。但是,您可以随意覆盖它 惯例。您可以通过将第二个参数传递给 belongsToMany 方法:

return $this->belongsToMany('App\Role', 'user_roles');

(Eloquent: Relationships #Many To Many)

在您的情况下,您需要像这样定义关系:

class User extends Model
{
    // other stuff

    createdDocuments()
    {
        return $this->belongsToMany('App\Document', 'document_user_created');
    }

    sentDocuments() // or receivedDocuments()
    {
        return $this->belongsToMany('App\Document', 'document_user_sent');
    }

    // other stuff
}


class Document extends Model
{
    // other stuff

    createdByUsers()
    {
        return $this->belongsToMany('App\User', 'document_user_created');
    }

    sentToUsers() // or sentFromUsers() or whatever it does mean
    {
        return $this->belongsToMany('App\User', 'document_user_sent');
    }

    // other stuff
}

【讨论】:

  • 我认为这在第二个参数中不起作用,因为它遵循规则。已经尝试过了,但我可以插入。
  • 究竟是什么不起作用?您尝试插入什么?
  • 我的意思是如果我不遵守 Laravel 的规则。我只是无法在我的数据透视表中插入值。
  • 你试过$document->sentToUsers()->attach($request->recipient_id);吗?
【解决方案2】:

您不需要另一个数据透视表。你需要一张这样的桌子:

public function up()
{
    Schema::create('revisions', function (Blueprint $table) {
        $table->increments('id');
        $table->integer('document_id')->unsigned();
        //Rest of table structure

        $table->foreign('document_id')->references('id')->on('document_user')->onDelete('cascade');
        $table->timestamps();
    });
}

当您需要创建新的修订版时:

$document = new Document;
//add $document attributes
$user->documents()->save($document);

$document->recipients->each(function($recipient){
      $id = $recipient->pivot->id;
      Revision::create(['document_id'=>$id]);
})

【讨论】:

  • 感谢您的解决方案! Revision 是我的模特吗?我对吗?如果我已经在我的document_user 中插入了一个值怎么办?如何在我的 1:M 中插入这个值?
  • 使用 Revision 是一个模型,抱歉没有提到它。你可以像我提到的那样插入它。通过集合上的find语句获取新的记录id,然后id使用pivot属性,我再补充说明。
  • 我现在要试试你的技巧和代码。我可以更新你吗?
  • 如何为我的document_user 表制作模型?我还是没有主意。
  • 你不需要那个,你只需要数据透视表ID,正如答案中提到的,你可以通过数据透视表得到它。
猜你喜欢
  • 2014-01-20
  • 2011-07-25
  • 1970-01-01
  • 1970-01-01
  • 2021-10-05
  • 1970-01-01
  • 1970-01-01
  • 2011-08-26
  • 1970-01-01
相关资源
最近更新 更多