簡體   English   中英

基於一對多關系檢索數據

[英]Retrieving data based on One To Many Relationship

我有兩個表稱為categoriesresources表。

基本上每個資源都有一個類別,類別 ID 保存在resources表中名為resource_category_id的列中。

所以為了建立模型之間的一對多關系,我做了這些:

Category :

class Category extends Model
{
    protected $table = "categories";
    protected $guarded = [];
    
    public function resources()
    {
        return $this->hasMany(Resource::class);
    }
}

Resource

class Resource extends Model
{
    protected $table = "resources";
    protected $guarded = [];
    
    public function category()
    {
        return $this->belongsTo(Category::class, 'resource_category_id');
    }
}

現在我想顯示所有類別和資源,並且具有相同的resource_category_id ,如下所示:

@php($menuCounter = 0)
@foreach($categories as $cat)
    <tr>
        <td style="text-align:center">{{ ++$menuCounter }}</td>
        <td style="text-align:center">{{ $cat->category_name }}</td>
        <td>
            <ul>
                @foreach($category->resources() as $resource)
                    <li><a href="{{ $resource->resource_link }}">{{ $ress->resource_name }}</a></li>
                @endforeach
            </ul>
        </td>
    </tr>
@endforeach

但是現在分類都出現了但是資源沒有顯示也沒有報錯!

那么這里出了什么問題?

如何通過 Eloquent 關系方法根據resource_category_id顯示資源?

代替:

@foreach($category->resources() as $resource)

@foreach($category->resources as $resource)

第一個是加載構建器,第二個是加載集合。

您還可以為類別 Model 中的資源關系指定外鍵:

public function resources()
{
    return $this->hasMany(Resource::class, 'resource_category_id');
}

暫無
暫無

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

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