简体   繁体   中英

How to create many-to-many relationship in Laravel

// the ticket migration 
Schema::create('tickets', function (Blueprint $table) {
    $table->increments('id');
    $table->integer('user_id')->unsigned();
    $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
    $table->string('title');
    $table->text('body');
    $table->timestamps();
});

// ticket and status 
Schema::create('statuses', function (Blueprint $table) {
    $table->increments('id');
    $table->string('name');
    $table->timestamps();
});

Schema::create('ticket_status', function (Blueprint $table) {    
    $table->integer('ticket_id')->unsigned();
    $table->integer('status_id')->unsigned();
    $table->primary(['ticket_id','status_id']);    
});

// store method
public function store()
{   
    $this->validate(request(), [
        'title' => 'required',
        'body' => 'required |min:5'
    ]);

    auth()
        ->user()
        ->tickets()
        ->create(request(['title','body','group','status','priority']));

    return redirect('/');
}

I have migration for my tickets and I have to get status_id and ticket_id .

When I use create method in my controller table status_ticket do not fill with data.

I do not have an error but my table is empty.

Try to use save, not create. Then the model should be attached

Have you used the methods belongsTo() and hasMany() in your new models?

If not, you have to add these and then you can easily save relations .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM