我需要计算每张专辑的图像数量

I need to show the number of images that user's each album has. For that I assume I need another join or a subquery but I'm not being able to achive the result I want.

$userId = auth()->user()->id;
$albums = DB::table('users_albums')
        ->join('albums', 'users_albums.albumId', '=', 'albums.id')
        ->where('users_albums.userId', $userId)
        ->select('albums.name', 
            'albums.owner', 
            'albums.id', 
            'albums.created_at')
        ->get();

Database structure:

EDIT:Added the following code and it worked. The issue now would be performance, but the main one is solved!

DB::raw('(SELECT 
    COUNT(I.id) 
FROM 
    images I
WHERE
    I.albumId = albums.id) as numberOfImages')

If you're using Eloquent and Models, you could quite easily do this using ->count().

Without Eloquent, you could look into something along these lines:

(These are obviously not EXACTLY what you need, but should guide you down the right path)

$album = DB::table('albums')->first();
$image_count = DB::table('images')->where('album_id', $album->id)->count();

More "eloquent" way:

// Album model:

public function images()
{
    return $this->hasMany('App\Image');
}

public function getImageCount()
{
    return $this->images->count();
}

// Controller

$first_album = auth()->user()->albums->first();
$album_image_count = $first_album->getImageCount();

hasManyThrough() is another Eloquent method you shouldn't overlook :)