使用 Laravel 插入与保存方法的关系

insert relationship with save method using Laravel

我有 2 个使用 Laravel 建立多对多关系的模型,我想在使用保存方法时插入关系 table。

我有为 child 创建新行的保存方法,我可以访问 parent id。

我需要在关系 table 中插入一个新行,使用我已经可以访问的 parent id 以及控制器中 create 函数创建的 id

型号

class Objective extends Model
{
           
public function subjects() {
    return $this->belongsToMany('App\Models\Subject');
}}

class Subject extends Model
{
   
public function objectives() {
    return $this->belongsToMany('App\Models\Objective');
}}

函数主题从 url 接收 parent 的 ID,创建函数也应该接收此 ID。

控制器

class ObjectiveController extends Controller
{
   
  public function subject($id) 
     {
        $subjects = Subject::find($id);
        $objectives = DB::table('objectives')->get();
        return view('admin.objectives.subject',['objectives' => $objectives],['subjects' => 
        $subjects],compact('objectives','subjects'));
     }   


 public function create($id)
    {
        $post = new Objective;
        $post->name = 'NEW OBJ';
        $post->save();
        return redirect('objectives');   
    }
}

路线

Route::get('objectives/create/{id}', [
    'uses' => 'App\Http\Controllers\ObjectiveController@create',
    'as' => 'admin.objectives'
    ]);

VIEW

<a class="card-header-action" href="{{url('objectives/create', ['id' => $subjects->id]) }}"><small class="text-muted">Add New</small></a>

您可以使用 attach 添加到主元 table:

...
$post->save();
$post->subjects()->attach($id);