Skip to content
Advertisement

Laravel Relationship Getting All Children

I have a query which returns a table. I would like to also return a list of styles which relate to it from another table. I have tried many things but I can’t find one which works. Any advice?

Query:

$data = YarnOrderLines::with('yarn_orders')
        ->with('yarns')->get(); //I would like to pull in YarnOrderLineStyles

YarnOrderLines:

protected $fillable = [
    'yarn_orders_id',
    'yarn_id',
    'qty',
    'price',
    'invoice_no',
    'qty_invoiced',
];
public function yarn_orders()
{
    return $this->belongsTo(YarnOrders::class);
}
public function yarns()
{
    return $this->belongsTo(Yarn::class);
}

public function yarn_order_line_styles()
{
    return $this->hasMany(YarnOrderLineStyles::class)->with('yarn_orders')->with('yarns');
}

YarnOrderLineStyles (table with relating styles in I would like to pull in)

protected $fillable = [
    'yarn_order_lines_id',
    'order_id',
];
public function yarn_order_lines()
{
    return $this->belongsTo(YarnOrderLines::class);
}

Advertisement

Answer

You’re already getting 2 relations from YardOrderLines, so you just need to add another with statement. You can combine them all into 1 line like this:

 YarnOrderLines::with(['yarn_orders', 'yarns', 'yarn_order_line_styles'])
    ->get();

And remove the with statement on your relation inside of YarnOrderLines, so it really doesn’t have a bearing on the Styles table.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement