Вот часть базы данных этого проекта, которая имеет отношение к вопросу:

- У одного пользователя может быть много заказов, но у каждого заказа есть только один пользователь (отношение «один ко многим»).
- В одном заказе может быть только один товар, но один товар может присутствовать во многих заказы (отношения «многие к одному»).
Код: Выделить всё
class User extends Authenticatable
{
// ...
/**
* Get orders of this user.
*
* @return Illuminate\Database\Eloquent\Relations\HasMany
*/
public function orders(): HasMany
{
return $this->hasMany(Order::class, 'client_id');
}
}
Код: Выделить всё
class Order extends Model
{
// ...
/**
* Get the client of this order.
*
* @return Illuminate\Database\Eloquent\Relations\BelongsTo
*/
public function client(): BelongsTo
{
return $this->belongsTo(User::class, 'client_id');
}
/**
* Get the ordered item.
*
* @return Illuminate\Database\Eloquent\Relations\BelongsTo
*/
public function item(): BelongsTo
{
return $this->belongsTo(Item::class, 'item_id');
}
}
Код: Выделить всё
class Downloadable extends Model
{
// ...
/**
* Get the orders having this item.
*
* @return Illuminate\Database\Eloquent\Relations\HasMany
*/
public function orders(): HasMany
{
return $this->hasMany(Order::class, 'item_id');
}
}
- Получать все элементы, упорядоченные по конкретного пользователя.
- Получить всех пользователей, которые заказали определенный товар.
Код: Выделить всё
/**
* Get items ordered by this user.
*
* @return ???
*/
public function items()
{
// What to do here?
}
Код: Выделить всё
/**
* Get users that ordered this item.
*
* @return ???
*/
public function users()
{
// What to do here?
}
Как один из возможные решения Я рассматриваю возможность использования staudenmeir/eloquent-has-many-deep, создания новой промежуточной таблицы с именем order_item для сопоставления заказов с элементами и использования следующего кода, например, для items метод:
Код: Выделить всё
/**
* Get items ordered by this user.
*
* @return ???
*/
public function items()
{
return $this->hasManyDeep(
Item::class,
[Order::class, 'order_item']
);
}
Подробнее здесь: https://stackoverflow.com/questions/790 ... e-intermed