Laravel как можно получить это отношение - PullRequest
1 голос
/ 10 января 2020

Рассмотрим digital store

Определение:

Buyer->all buyer
Products->all products
Downloads->store those products that buyer bought

Buyer можно купить Product и хранить в Downloads, сейчас Я хочу показать покупателю список загрузок.

ProductController. php

public function buyerproducts()
{
    $user = auth()->guard('buyer')->user();
    if ($user) {
        $files = Product::where('deleted', 0)
            ->where('deleted', 0)
            ->with('files', 'province:id,name', 'city:id,name')
            ->get();

        // and here I got a loop.. to add some extra data
        return response()->json(['data' => $files], 200);
    } else {
        return response()->json(['success' => 'no content'], 204);
    }
}

Product. php

function files()
{
    return $this->hasManyThrough('App\Download', 'App\Buyer', 'id', 'product_id', 'buyer_id', 'id');
}

Но он возвращает все данные, а не то, что покупатель купил. Есть идеи? Обратите внимание, что я должен получить эти данные в контроллере продукта, а не загрузить.


Продукты:

-----------------------
|id | name  | seller_id  |
-----------------------
| 1 | bmw   |    1     |
-----------------------
| 2 | benz  |    1     |
-----------------------
| 2 | reno  |    2     |
-----------------------

Скачиваний:

------------------------------
|id | product_id  | buyer_id  |
------------------------------
| 1 |     1     |      1      |
------------------------------
| 2 |     1     |      2      |
------------------------------
| 3 |     2     |      22     |
------------------------------

Покупатель:

------------------------------
|id | name     |       email  |
------------------------------
| 1 |     john     |      @   |
------------------------------
| 2 |     mike     |      @   |
------------------------------
| 3 |     dave     |      @  |
------------------------------

Ответы [ 2 ]

1 голос
/ 10 января 2020

Отношение HasManyThrough предполагает отношения от go до 2 hasMany, однако, глядя на определение вашей таблицы, первое отношение - hasMany, а второе - belongsTo. Поскольку оба ключа относятся к одной строке в другой таблице (обе belongsTo), вместо этого мы можем вместо этого создать отношение belongsToMany и рассматривать таблицу downloads как сводную.


Вы можете go об этом по-разному.

Во-первых, я бы предложил установить отношения между Buyer и Product (если вы этого еще не сделали):

Продукт

public function buyers()
{
    return $this->belongsToMany(Buyer::class, 'downloads')->withTimestamps();
}

Покупатель

public function products()
{
    return $this->belongsToMany(Product::class, 'downloads')->withTimestamps();
}

Тогда в вашем методе контроллера вы можете оставить тот же запрос и используйте whereHas () :

public function buyerproducts()
{
    $user = auth()->guard('buyer')->user();

    if ($user) {
        $files = Product::where('deleted', 0)
            ->whereHas('buyers', function ($query) use ($user) {
                $query->where('buyers.id', $user->id);
            })
            ->with('files', 'province:id,name', 'city:id,name')
            ->get();

        // and here I got a loop.. to add some extra data
        return response()->json(['data' => $files], 200);
    }

    return response()->json(['success' => 'no content'], 204);
}

или в качестве альтернативы, вы не можете просто запросить товар прямо у $user (покупатель):

public function buyerproducts()
{
    $user = auth()->guard('buyer')->user();

    if ($user) {
        $files = $user->products()->where('deleted', 0)
            ->whereHas('buyers', function ($query) use ($user) {
                $query->where('buyers.id', $user->id);
            })
            ->with('files', 'province:id,name', 'city:id,name')
            ->get();

        // and here I got a loop.. to add some extra data
        return response()->json(['data' => $files], 200);
    }

    return response()->json(['success' => 'no content'], 204);
}
0 голосов
/ 10 января 2020

Почему бы вам go не получить продукты как отношения объекта Покупателя.

Таким образом, вы определяете продукты в Покупателе. php:

function products()
{
    return $this->hasManyThrough('App\Download', 'App\Product', 'id', 'buyer_id', 'product_id', 'id');
}

И в контроллере Вы можете назвать это как:

$buyer->with([
  'products.province:id,name',
  'products.city:id,name'
  ])
    ->whereHas('products', function($query){
       $query->where('deleted', 0)
      })
    ->get()

тогда вы можете go с return response()->json(['data' => $buyer->products], 200);

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...