Laravel 5.1 - Connecting multiple tables

I have the following tables:

Customer
    id

Order
    id
    customer_id

Order_notes
    order_id
    note_id

Notes
    id

If I want to get all the order notes for a customer so that I can do the following, how can I do this? Is there a way to define relationships in my model that go through several pivot tables to join a customer to order notes?

@if($customer->order_notes->count() > 0)
    @foreach($customer->order_notes as $note)
        // output note
    @endforeach
@endif
+4
source share
3 answers

In the end, I just did the following:

class Customer extends Model
{
    public function order_notes()
    {
        return $this->hasManyThrough('App\Order_note', 'App\Order');
    }
}

class Order_note extends Model
{
    public function order()
    {
        return $this->belongsTo('App\Order');
    }

    public function note()
    {
        return $this->belongsTo('App\Note')->orderBy('notes.id','desc');
    }
}

Then refer to the notes as follows:

@foreach($customer->order_notes as $note)
    echo $note->note->text;
@endforeach
0
source

Create this relationship on your models.

class Customer extends Model
{
    public function orders()
    {
        return $this->hasMany(Order::class);
    }

    public function order_notes()
    {
        // have not tried this yet
        // but I believe this is what you wanted
        return $this->hasManyThrough(Note::class, Order::class, 'customer_id', 'id');
    }
}

class Order extends Model
{
    public function notes()
    {
        return $this->belongsToMany(Note::class, 'order_notes', 'order_id', 'note_id');
    }
}

class Note extends Model
{

}

You can get the relationship using this query:

$customer = Customer::with('orders.notes')->find(1);
+2
source

' ToMany'? . -

$customer->belongsToMany('OrderNote', 'orders', 'customer_id', 'id');

Of course, it will not work directly if you want to also receive an order object (but maybe you can use withPivot)

0
source

Source: https://habr.com/ru/post/1610247/


All Articles