使用 Eloquent laravel 从父模型中选择某些列

selecting certain columns from parent model with Eloquent laravel

我为 Content

的名称制作模式
class Content extends Model
{
    /**
     * The attributes that aren't mass assignable.
     *
     * @var array
     */
    protected $guarded = [];

    /**
     * Get Images
     *
     * @return \Illuminate\Database\Eloquent\Relations\HasMany
     */
    public function images()
    {
        return $this->hasMany(Image::class, 'content_id')->orderBy('sort');
    }
}

我仍然在 controller

中使用以下代码
$data = \App\Models\Content::has('images')
                                   ->leftJoin('content_relations AS r', 'contents.id', '=', 'r.content_id')
                                   ->leftJoin('products AS p', 'contents.id', '=', 'p.content_id')
                                   ->whereIn('r.category_id', [1, 2, 3])
                                   ->groupBy('contents.id')->take(4)->get();

当我打电话时,它会给我图像记录

foreach ($data as $row) {
    var_dump($row->images);
}

如果我更改了 controller 中的代码以从 Content Model 中获取某些列,只需添加 select 函数

$data = \App\Models\Content::has('images')->select('title', 'cover', 'slug')
                                           ->leftJoin('content_relations AS r', 'contents.id', '=', 'r.content_id')
                                           ->leftJoin('products AS p', 'contents.id', '=', 'p.content_id')
                                           ->whereIn('r.category_id', [1, 2, 3])
                                           ->groupBy('contents.id')->take(4)->get();

那就不是return数据在

foreach ($data as $row) {
    var_dump($row->images);
}

您在没有 ID 的 $data 上调用图像关系

您在内容 class 中的图像功能将需要 content_id。 所以你在取数据的时候必须selectid,

试试这个

$data = \App\Models\Content::has('images')->select('content.id','title', 'cover', 'slug')
                                       ->leftJoin('content_relations AS r', 'contents.id', '=', 'r.content_id')
                                       ->leftJoin('products AS p', 'contents.id', '=', 'p.content_id')
                                       ->whereIn('r.category_id', [1, 2, 3])
                                       ->groupBy('contents.id')->take(4)->get();

您必须为您的内容行添加 id,因为我想这就是将图像 link 编辑到您的内容模型的方式。如果不包含此内容,则无法 link 这些图像的内容模型。

此外,考虑使用 eager loading,这将预先加载所有图像并使用较少的查询。

$data = \App\Models\Content::has('images')
    ->with('images')
    ->select('id', 'title', 'cover', 'slug')
    ->leftJoin('content_relations AS r', 'contents.id', '=', 'r.content_id')
    ->leftJoin('products AS p', 'contents.id', '=', 'p.content_id')
    ->whereIn('r.category_id', [1, 2, 3])
    ->groupBy('contents.id')->take(4)->get();

您还应该为产品创建关系,这将使您的代码更简洁,并允许在此处预先加载。