Populate laravel object with relationships

oBo

I want to populate Every CustomerEvent with the Customer related to the CustomerEvent.

When I Loop through the object and call to $customerevent->customer foreach object I can get the customer related to that event but Can I populate the all objects in the main object without looping through every single event ?

I want to do something like this:

$typeOne = CustomerEvent::typeOne()->get();
$customersWithTypeOne = $typeOne->Customers;

Here my code:

Table 1: "events"

id, customer_id

Model for Table 1 "CustomerEvent":

<?php

class CustomerEvent extends Eloquent{
    protected   $guarded = ['id'];
    public      $table = "event";
    protected   $softDelete = true;

    public function scopeTypeOne($query)
    {
        $followUps = $query->where('type_id', '=', '1');
    }


    public function Customers()
    {
        return $this->belongsTo('Customer', 'customer_id');
    }
}

Table 2: "customers"

id

Model for Table 2 "Customers":

<?php class Customer extends BaseModel{
    protected $guarded = ['id'];
}

EventController:

public function index()
{
    $typeOne = CustomerEvent::typeOne()->get();
    $customersWithTypeOne = $typeOne->Customers;
    dd($customersWithTypeOne);
}
cheelahim

From you database scheme I see customer has many events, so I would recommend to define this relationship in you Customer model.

class Customer extends BaseModel{
    protected $guarded = ['id'];

    public function events()
    {
        return $this->hasMany('CustomerEvent', 'customer_id');
    }
}

Then you will be able to query customers with events:

$customersWithTypeOne = Customer::whereHas('events', function($query){
    $query->where('type_id', 1);
})->get()

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related