this is navigation schema
Schema::create('navigations', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('name');
$table->timestamps();
});
this is sub navigation schema
Schema::create('sub_navigations', function (Blueprint $table) {
$table->bigIncrements('id');
$table->bigInteger('nav_id')->unsigned()->index();
$table->string('name');
$table->timestamps();
$table->foreign('nav_id')->references('id')->on('navigations')->onDelete('cascade');
});
this is navigation model
public function subnavigations(){
return $this->hasMany('App\Model\Admin\Sub_navigation');
}
this is sub navigation model
public function navigation(){
return $this->belongsTo('App\Model\Admin\Navigation');
}
controller's code
public function store(Request $request)
{
//return $request->all();
$sub_navigation = new Sub_navigation;
$sub_navigation->name = $request->name;
$sub_navigation->nav_id = $request->navigation[0];
//return $sub_navigation;
//$sub_navigation->save();
$navigation = Navigation::find($request->navigation[0]);
// $navigation->subnavigations()->save($sub_navigation);
//return $navigation;
$sub_navigation->navigation()->associate($navigation);
$sub_navigation->save();
return redirect()->back();
}
this is error message
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'navigation_id' in 'field list' (SQL: insert into `sub_navigations` (`name`, `nav_id`, `navigation_id`, `updated_at`, `created_at`) values (Philosophy, 2, 2, 2019-11-25 02:17:33, 2019-11-25 02:17:33))
From the docs:
One To Many
Remember, Eloquent will automatically determine the proper foreign key column on the
Sub_navigation
model. By convention, Eloquent will take the "snake case" name of the owning model and suffix it with_id
. So, Eloquent will assume the foreign key on theSub_navigation
model isnavigation_id
. You can override the foreign key by passing additional argument to thehasMany
method:
/**
* Get the subnavigations for the navigation.
*/
public function subnavigations(){
return $this->hasMany('App\Model\Admin\Sub_navigation', 'nav_id');
}
Eloquent will try to match the
navigation_id
from theSub_navigation
model to an id on theNavigation
model. Eloquent determines the default foreign key name by examining the name of the relationship method and suffixing the method name with a_
followed by the name of the primary key column. However, if the foreign key on theSub_navigation
model is notnavigation_id
, you may pass a custom key name as the second argument to thebelongsTo
method:
/**
* Get the navigation that owns the sub_navigation.
*/
public function navigation()
{
return $this->belongsTo('App\Model\Admin\Navigation', 'nav_id');
}
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.