简体   繁体   English

Laravel – 获取关系计数

[英]Laravel – Get relationship count

I'm new to laravel.我是 Laravel 的新手。 I used laravel 5.4我使用了 Laravel 5.4

I have this problem and I dont know where to start.我有这个问题,我不知道从哪里开始。

I want to count all assets in Storage where all of its category is Electronic.我想计算 Storage 中所有类别为电子的所有资产。

Heres my Table:这是我的表:

Assets资产

 -- 
 id
 asset_name
 asset_type_id (fk)

AssetType资产类型

 --
 id
 asset_type
 category_id (fk)

Category类别

 --
 id
 category

Heres my defined model:这是我定义的模型:

Asset Model资产模型

public function assetType(){
     return $this->belongsTo(AssetType::class);
}
public function category(){
     return $this->belongsTo(Category::class);
}

AssetType Model资产类型模型

public function category(){
     return $this->belongsTo(Category::class);
 }

public function assets(){
     return $this->hasMany(Asset::class);
}

Category Model类别模型

public function types(){
     return $this->hasMany(AssetType::class);
}

Controller:控制器:

AssetController资产控制器

public function index()
    {
        $result = Asset::all();

        return view('asset.index', compact('result'));
    }

View:看法:

index.blade索引刀片

@foreach($result as $asset)
<tr>

    <td>{{ $asset->asset_name }}</td>
    <td>{{ $asset->assetType->asset_type}}</td>
    <td>{{ $asset->assetType->category->category}}</td>


</tr>
@endforeach

Sample Result:示例结果:

Asset: DELL
Asset Type: Laptop
Category: Electronic

With that I can view all assets.有了它,我可以查看所有资产。

I'm trying to get the count of all assets whose category is Electronic in controller and pass it to view.我正在尝试获取控制器中类别为电子的所有资产的数量并将其传递给查看。 Please enlighten me I'm lost.请赐教我迷路了。

You may use a Has Many Through relationship on your Category like so.您可以像这样在您的Category上使用Has Many Through关系。

Category Model类别模型

public function assets()
{
    return $this->hasManyThrough(Asset::class, AssetType::class);
}

With this you can easily reach Asset from Category .有了这个,您可以轻松地从Category访问Asset Now count your assets in your controller:现在计算控制器中的assets

Category::where('category', 'Electronic')->withCount('assets')->get();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM