OutForCode
OutForCode

Reputation: 461

Eloquent join returns empty data set

I am trying to join 3 tables, are - customer, customer_item and items.

Customer - model

public function itemRel(){
    return $this->hasMany(CustomerItem::class,'customer_id');
}

CustomerItem - model

public function itemDetails(){  
    return $this->hasOne(Items::class, 'id');
}

CustomerController

$customer = Customers::find($id);
$data = $customer->itemRel();
return $data;

Schema structure

customer - [id,name,mobile,username...]
items - [id, item_name, quantity, nature ....]
customer_item - [id, customer_id,item_id...]

I want to list all the items that related to the user (customer_item)

Upvotes: 0

Views: 216

Answers (4)

Adlan Arif Zakaria
Adlan Arif Zakaria

Reputation: 1745

Try to use belongsToMany relation instead

Customer - model

public function items(){
    return $this->belongsToMany(Items::class,'customer_item','customer_id','item_id');
}

Items - model

public function customers(){    
    return $this->belongsToMany(Customer::class,'customer_item','item_id','customer_id');
}

CustomerController

$customer = Customers::find($id);
$data = $customer->items();
return $data;

Upvotes: 1

AddWeb Solution Pvt Ltd
AddWeb Solution Pvt Ltd

Reputation: 21681

Please change your model code like:

Customer - model

public function itemRel(){
    return $this->belongsTo(CustomerItem::class,'customer_id');
}

CustomerItem - model

public function customer(){  
    return $this->hasMany(Customer::class);
}

Updated Answer

Customer - model

public function itemRel(){
    return $this->hasMany(CustomerItem::class);
}

CustomerItem - model

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

Upvotes: 0

Volod
Volod

Reputation: 1437

Use it without parenthesis

$data = $customer->itemRel;

to get actual model data use

$data->propertyName

Upvotes: 0

Inzamam Idrees
Inzamam Idrees

Reputation: 1981

Try this:

$customer = Customers::with('itemRel')->find($id);
$data = $customer->itemRel;
return $data;

I hope it would be helpful.

Upvotes: 0

Related Questions