php Laravel:保存belongsToMany 关系

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30704908/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 22:00:56  来源:igfitidea点击:

Laravel : Saving a belongsToMany relationship

phplaravellaravel-5

提问by Yobogs

I want to save a new signature in my table signature. Each signature can be linked to multiples users. I have a many to many table between Users and Signatures.

我想在我的表签名中保存一个新签名。每个签名可以链接到多个用户。我在用户和签名之间有一个多对多的表。

My Model Signature is :

我的模型签名是:

class Signature extends Model {
   public $fillable = ['name', 'template'];

   public function users() {
       return $this->belongsToMany('App\User');
   }
}

My Controller SigantureController.php is :

我的控制器 SignatureController.php 是:

public function store(CreateSignaturesRequest $request)
{
    //return $user_id;
    $values = $request->only(['name','template']);

    Signature::create($values));

    return response()->json(['message'=>'SUCCESS'], 201);

}

How can I do to Create my Signature and link it to a user ?

如何创建我的签名并将其链接到用户?

I tried

我试过

Signature::create($values)->associate($user_id);

Thanks

谢谢

回答by fahad.hasan

Considering your tables are users, signatures and user_signatures

考虑到您的表是用户、签名和 user_signatures

Define the relation in model: User.php

在模型中定义关系:User.php

class User extends Model {
   public function signatures() {
       return $this->belongsToMany('\App\Signature', 'user_signatures');
   }
}

Define the inverse of the relation in model: Signature.php

在模型中定义关系的逆:Signature.php

class Signature extends Model {    
   public function users() {
       return $this->belongsToMany('\App\User', 'user_signatures');
   }
}

In your controller you could do the following:

在您的控制器中,您可以执行以下操作:

//create a new signature
$signature = new Signature($values);
//save the new signature and attach it to the user
$user = User::find($id)->signatures()->save($signature);

The opposite is possible too:

相反的也是可能的:

$user = User::find($user_id);
$signature = Signature::create($values)->users()->save($user);

Alternatively if you have an existing signature you should do:

或者,如果您有现有签名,则应该执行以下操作:

$user = User::find($id);
$user->signature()->attach($signature->id);

Please note that attach() and detach() accepts an id or an array of ids.

请注意 attach() 和 detach() 接受一个 id 或一组 id。

Laravel docs has covered this in much more details and better examples. You should check attach(), detach() and sync() methods. Please have a look: http://laravel.com/docs/5.0/eloquent#inserting-related-models

Laravel 文档已经涵盖了更多细节和更好的例子。您应该检查 attach()、detach() 和 sync() 方法。请看一看:http: //laravel.com/docs/5.0/eloquent#inserting-related-models

回答by Saiyan Prince

You need to have a table called user_signaturewith the following schema:

您需要有一个user_signature使用以下架构调用的表:

$table->integer('user_id')->unsigned();
$table->integer('signature_id')->unsigned();

$table->foreign('user_id')->references('id')->on('users');
$table->foreign('signature_id')->references('signatures')->on('users');

Then your Usermodel should have the following method:

那么你的User模型应该有以下方法:

Model User

Model User

public function signatures() {
    return $this->belongsToMany('App\Signature');
}

Now that you have developed the Many-To-Manyrelationship between the models what you can do is this:

现在您已经开发了Many-To-Many模型之间的关系,您可以做的是:

While storing a new record (the controller you are using for the signature):

在存储新记录时(您用于签名的控制器):

 /**
 * Insert the signature
 *
 * @param Request $request
 * @return ...
 */
 public function store( Request $request ) {
    // your validation

    $signature->users()->attach( $request->input('user_id') );

    // return
}

Similarly while updating the record (the controller you are using for signature):

同样,在更新记录(您用于签名的控制器)时:

/**
 * Update the signature with the particular id
 *
 * @param $id
 * @param Request $request
 * @return ...
 */
 public function update( $id, Request $request ) {
    // your validation

    $signature->users()->sync( $request->input('user_id') );

    // return
}

回答by Yasen Zhelev

First of all associaterequires a model object to be passed as arguments. See here: http://laravel.com/api/5.0/Illuminate/Database/Eloquent/Relations/BelongsTo.html#method_associate

首先associate需要一个模型对象作为参数传递。见这里:http: //laravel.com/api/5.0/Illuminate/Database/Eloquent/Relations/BelongsTo.html#method_associate

Is is also for belongsTorelationships, not Many to Manyas is in your case. See here: http://laravel.com/docs/5.0/eloquent#inserting-related-models

Is 也适用于belongsTo关系,而不是Many to Many您的情况。请参阅此处:http: //laravel.com/docs/5.0/eloquent#inserting-related-models

Based on that what you should do is:

基于此,您应该做的是:

Signature::create($values)->users()->attach($user_id);