簡體   English   中英

如何使用 Eloquent 關系做到這一點

[英]How can I do this with Eloquent Relationship

我正在處理一個在線商店項目,我想創建添加到收藏夾系統,以便用戶將他們喜歡的產品添加到他們最喜歡的列表中。

所以我創建了一個名為favourite_products的表,如下所示:

在此處輸入圖像描述

所以usr_id代表用戶 id, prd_id代表產品 id。

這是User.php Model:

public function favourites()
    {
        return $this->belongsToMany(Product::class, 'favourite_products', 'usr_id', 'prd_id')->withTimestamps();
    }

這是Product.php Model:

public function favouritees()
    {
        return $this->belongsToMany(User::class, 'favourite_products', 'prd_id', 'usr_id');
    }

現在我想從這個表中獲取所有數據。

所以我嘗試將它添加到 Controller 中:

public function index()
    {
        $favouriteProducts = FavouriteProduct::all();
        return view('admin.shop.favourites.all', compact('favouriteProducts'));
    }

然后在刀片中:

@foreach($favouriteProducts as $fav_pro)
    @php
        $member_info = \App\User::where($fav_pro->usr_id)->first();
        $product_info = \App\Shop\Product::find($fav_pro->prd_id);
    @endphp 
    <tr class="closest-tr">
        <td>{{ ++$menuCounter }}</td>
        <td>{{ $member_info->usr_name }}</td>
        <td>{{ $product_info->prd_name }}</td>
    </tr>
@endforeach

但我想知道,如何通過用戶和產品模型關系檢索usr_nameprd_name 因此,我不需要在視圖中添加 Model 名稱並在那里獲取數據......

我在 Controller 上試過這兩個,但這些都是錯誤的:

Product::whereHas('favouritees')->get(); // if two different users add same product, it returns only one of them

User::whereHas('favourites')->get(); // if a user add different products, it returns only one of them for the user

所以問題是,如何在具有用戶或產品多對多關系的表中顯示favourite_products的所有結果?

當您使用 pivot model 時,您可以在您的FavouriteProduct產品 model 中添加這些關系:

public function user()
{
    return $this->belongsTo(User::class, 'usr_id');
}

public function product()
{
    return $this->belongsTo(Product::class, 'prd_id');
}

現在在你的刀片文件中:

@foreach($favouriteProducts as $fav_pro)
    <tr class="closest-tr">
        <td>{{ ++$menuCounter }}</td>
        <td>{{ $fav_pro->user->usr_name }}</td>
        <td>{{ $fav_pro->product->prd_name }}</td>
    </tr>
@endforeach

也不要忘記在您的 controller 中with您的查詢

public function index()
{
    $favouriteProducts = FavouriteProduct::with('product', 'user')->all();
    return view('admin.shop.favourites.all', compact('favouriteProducts'));
}

獲取所有數據(產品和最喜歡該產品的用戶)獲取所有產品以及與其相關的用戶

$products = Product::whereHas('favouritees')->with('favouritees')->get(); 
// if two different users add same product, it returns only one of them but it will have two users in the relation favouritees

然后在你的刀片中你可以循環它們

@foreach($products as $product)
    @foreach($product->favouritees as $user)    
        <tr class="closest-tr">
            <td>{{ ++$menuCounter }}</td>
            <td>{{ $user->usr_name }}</td>
            <td>{{ $product->prd_name }}</td>
        </tr>
    @endforeach
@endforeach

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM