Create and Insert Many-to-Many Relationships in Laravel

霸气de小男生 提交于 2021-01-29 15:07:40

问题


First of all, i'm a beginner and trying to learn all i can. So if i have mistakes please correct me.

So, i am working on a laravel project. I've got two models; drugs and interactions. What i am struggling is, I want to add two drugs and one interaction in one form. But also, i want to check if the drug has inserted already to avoid duplicate data.

Here are my models:

class Drug extends Model
{
//Table Name
protected $table = 'drugs';
//Primary Key
public $primaryKey = 'id';
//Timestamps
public $timestamps = true;
//relationship
public function interactions()
{
return $this->belongsToMany('App\Interaction', 'drug_interaction', 'interaction_id', 'drug_id');
}
}


 class Interaction extends Model
    {
    //Table Name
    protected $table = 'interactions';
    //Primary Key
    public $primaryKey = 'id';

    //Timestamps
    public $timestamps = true;
    //Relationship
    public function drugs()
    {
    return $this->belongsToMany('App\Drug', 'drug_interaction', 'drug_id', 'interaction_id');
    }
    }

And this is simply the store function in my DrugsController

public function store(Request $request)
{
    $this->validate($request, [
        'name'=> 'required',
        'info'=> 'nullable'
    ]);


    //create drug
    $drug = new Drug;
    $drug->name = $request->input('name');
    $drug->info = $request->input('info');

    $drug->save();

    return redirect('/drugs')->with('success', 'İlaç Eklendi');
}

And this is my InterationsController's store function.

public function store(Request $request)
{
    $this->validate($request, [
        'name'=> 'required',
        'description'=> 'required',
        'category'=> 'nullable'
    ]);


    //create interaction
    $interaction = new Interaction;
    $interaction->name = $request->input('name');
    $interaction->description = $request->input('description');
    $interaction->category = $request->input('category');
    $interaction->save();

I can attach relationships via artisan tinker so i think relationship works. But i stuck when it comes to multiple input forms goes to different controllers. But using static id's. I need to make it variables. But two drugs should be attached to one interaction. So i couldn't succeed pasing two variables from form at the same time.

In dumb words, what i am trying to achieve is;

  • request drug_name_one from form's first textbox. Check db for that drug name, if exists; get its id. If it doesn't then create one and get id.
  • request drug_name_two from form's second textbox. Do the same as step one.
  • create an interaction as typed in form's third text box.
  • attach them.

PS: after this attach() work done, i also couldn't find a way to search for two drugs if they have a common interaction. If you can also mention a few tips to achieve that i'll be grateful.

All help and further reading advices appreciated. Thanks All !

Edit:

This is the create_interactions migration.

Schema::create('interactions', function (Blueprint $table) {
     $table->BigIncrements('id');
     $table->string('name');
     $table->string('description');
     $table->string('category');
     $table->timestamps();
            });
        }

This is the input for 'category' field:

 <div class="form-group">
        {{Form::label('category', 'Kategori')}}
        {{Form::text('category', '', ['class' => 'form-control', 'placeholder' => 'Etkileşim Kategorisi'])}}
    </div> 

I couldn't make the structure of a form as i desired btw. It's just the form for creating interactions by itself without relationship.


回答1:


Here is the solution. It is working well now.

First of all i was trying to assign 2 drugs to one interaction. So i've imported select2 and used this "select" form to list the drugs and chose multiple from them:

 <div class="form-group">
                    {!! Form::label('İlaçları Seçin') !!}
                    {!! Form::select('drugs[]', $drugs, null, ['multiple' => 'multiple', 'class' => 'form-control drugs']) !!}
                </div>

On the InteractionsController:

$interaction = new Interaction;

        $interaction->name = $request->input('name');
        $interaction->description = $request->input('description');
        $interaction->category = $request->input('category');

        $interaction->save();

        $interaction->drugs()->sync($request->drugs, false);

But i also wanted to show and edit those drugs assigned to the specific interaction. So on the edit.blade.php form there is this script:

<script type="text/javascript">
        $('.drugs').select2().val({!! json_encode($interaction->drugs()->allRelatedIds()) !!}).trigger('change');
    </script>

This script, calls the related drugs to the selected interaction in the same form as i used in create.blade.



来源:https://stackoverflow.com/questions/60858629/create-and-insert-many-to-many-relationships-in-laravel

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!