Company Model
class Company extends Model {
public function position() {
return $this->hasMany('App\Position);
}
}
Position Model
class Position extends Model{
public function company() {
return $this->belongsTo('App\Company);
}
}
companies table: id_company , company_name
positions table: id_position , position , company_id (foreign key)
What I'm trying to do is to create a dropdown list of every company name so i can reference the id of that company so i can store it as the foreign key (company_id).
Form for storing to positions table
{!! Form::open(['action' => 'PostionController@store', 'method' => 'POST', 'enctype' => 'multipart/form-data']) !!}
<div class="form-group">
{{Form::label('position', 'Position')}}
{{Form::text('position', '', ['class' => 'form-control', 'placeholder' => 'Position'])}}
</div>
//Reference to the id
<div class="form-group">
{{Form::select(!!!Array generated from the Company table!!!")}};
</div>
{{Form::submit('Submit', ['class'=>'btn btn-primary'])}}
{{Form::reset('Reset', ['class'=>'btn btn-danger'])}}
{!! Form::close() !!}
I'm new to Laravel so any reference to read it would be a great help Thank you!
You can specify foreign key name in hasMany()
and belongsTo()
in second parametr.
Company Model
class Company extends Model {
public function position() {
return $this->hasMany(App\Position::class, 'company_id');
}
}
Position Model
class Position extends Model{
public function company() {
return $this->belongsTo(App\Company:class, 'company_id');
}
}
To get company positions:
{{ Form::select('name',\App\Company::find($id)->position()->get()->toArray())}}
Or you can get company by position:
\App\Position::find($id)->company()->get()->toArray()
Be carefull. Don't use get()
with only find()
method. This will return you all rows in your table. You can use get()
after using relation function.
用这个:
{!! Form::select('company_id', \App\Company::pluck('company_name', 'id_company')) !!}
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.