简体   繁体   中英

Laravel – Get relationship count

I'm new to laravel. I used 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.

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 Model

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

With this you can easily reach Asset from Category . Now count your assets in your controller:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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