Php 使用雄辩的laravel从父模型中选择某些列

Php 使用雄辩的laravel从父模型中选择某些列,php,model,laravel-5.2,relationship,Php,Model,Laravel 5.2,Relationship,我为内容的名称设置模式 class Content extends Model { /** * The attributes that aren't mass assignable. * * @var array */ protected $guarded = []; /** * Get Images * * @return \Illuminate\Database\Eloquent\Relation

我为内容的名称设置模式

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');
    }
}
我仍然在控制器中使用以下代码

$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);
}
如果我更改了控制器中的代码,以便从内容模型获取特定列,则只需添加选择功能

$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();
那么它就不会返回数据了

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

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

内容类中的图像函数将需要内容id。 因此,在获取数据时,必须选择id

试试这个

$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
,因为我想这就是图像链接到内容模型的方式。如果不包含此内容,则无法将内容模型链接到这些图像

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

$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();

您还应该为产品创建一个关系,这将使您的代码更加清晰,并允许在此处进行快速加载。

很高兴帮助imran。请接受这个答案,因为它帮助了其他遇到这种问题的人