Many-to-Many Query and Junk Download
I'm new to Laravel, I was able to query a Many-to-Many relationship. Where "template_dynamic" is the pivot of the two tables "template" and "dynamic".
// Template Model
class Template extends Eloquent
{
protected $table = 'template';
protected $guarded = array('template_id');
protected $primaryKey = 'template_id';
public function dynamic()
{
return $this->belongsToMany('dynamic', 'template_dynamic')
->select('*')
->withPivot('template_dynamic_id')
->orderBy('template_dynamic_html_sort', 'ASC');
}
here i managed to get records
// Template Controller
$dynamic_fields = Template::find($rec->template_id)->dynamic;
what I want to do now is that there are - many properties 'template_dynamic_option' in the pivot table. How can I query the records and combine them with the $ dynamic_fields variable?
// What I want to do is something like this. But sadly this is an invalid syntax
$dynamic_fields = $dynamic_fields->with('template_dynamic_option');
Any recommendations or improvements are appreciated.
Thanks in advance.
source to share
First, I'm sure you don't need select('*')
relationships in your query.
But back to your real problem;)
Accessing a pivot table in Eloquent is pretty simple.
$dynamic_fields = Template::find($rec->template_id)->dynamic;
foreach($dynamic_fields as $dynamic){
var_dump($dynamic->pivot)
}
The point is that by default only pivot table keys are present in the object. To change this, you must define them with withPivot()
. Really like you, but not with an ID.
public function dynamic()
{
return $this->belongsToMany('dynamic', 'template_dynamic')
->withPivot('template_dynamic_option')
->orderBy('template_dynamic_html_sort', 'ASC');
}
And if you have multiple extra columns use this syntax:
->withPivot('template_dynamic_option', 'foo', 'bar');
source to share