Eloquent join возвращает пустой набор данных - PullRequest
0 голосов
/ 12 февраля 2019

Я пытаюсь объединить 3 таблицы: - customer, customer_item и items.

  • покупатель - данные покупателя
  • товары - подробности товара
  • customer_item - отношение покупателя к товарам

покупатель - модель

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

CustomerItem - модель

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

CustomerController

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

Структура схемы

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

Я хочу перечислить все элементы, связанные спользователь (customer_item)

Ответы [ 4 ]

0 голосов
/ 12 февраля 2019

Попробуйте использовать belongsToMany отношение вместо

Заказчик - модель

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

Элементы - модель

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

CustomerController

$customer = Customers::find($id);
$data = $customer->items();
return $data;
0 голосов
/ 12 февраля 2019

Попробуйте это:

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

Надеюсь, это будет полезно.

0 голосов
/ 12 февраля 2019

Используйте его без скобок

$data = $customer->itemRel;

, чтобы получить фактические данные модели, используйте

$data->propertyName
0 голосов
/ 12 февраля 2019

Пожалуйста, измените код вашей модели следующим образом:

Клиент - модель

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

CustomerItem - модель

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

Обновленный ответ

Клиент - модель

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

CustomerItem - модель

public function customer(){  
    return $this->belongsTo(Customer::class, 'customer_id');
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...