【问题标题】:whereHas on multiple relationships - laravel 5.4whereHas 有多个关系 - laravel 5.4
【发布时间】:2023-03-09 21:52:02
【问题描述】:

我有多个表。

旅游表

id | title | slug .....

图像表

id | tour_id | image.....

包含表

id | tour_id | inclusion....

排除表

id | tour_id | exclusion...

项目表

id | tour_id | day_summary.....

Tour_User 表(This is a pivot table between tour table and user table)

tour_id | user_id

我需要

我想通过image, inclusion, exclusion, itenary, tour user 获取旅游详情,其中image.tour_id 等于tour.idinclusion.tour_id 等于tour.idexclusion.tour_id 等于tour.id 等等。

我已将Tour Model 中的关系定义为

public function user() {
        return $this->hasOne(TourUser::class);
    }

    public function image() {
        return $this->hasMany(TourImage::class);
    }

    public function inclusion() {
        return $this->hasMany(TourInclusion::class);
    }

    public function exclusion() {
        return $this->hasMany(TourExclusion::class);
    }

    public function highlight() {
        return $this->hasMany(TourHighlight::class);
    }

    public function itenary() {
        return $this->hasMany(TourItenary::class);
    }

我知道这可以通过循环和条件语句来完成,我们需要多次查询数据库,但是我想通过在 Laravel 5.4 中使用 eloquent 的 `eager loading 来实现它我该如何实现它。 https://stackoverflow.com/a/21380265/4807414这个好像有一点类似的问题但是没能解决。

我尝试了类似的方法:

$tour = Tour::where('slug', $slug)
                    ->with('user', 'image', 'itenary', 'inclusion', 'exclusion')
                    ->whereHas('user',  function($query) {
                        $query->where('user_id', user()->id); }) <-- user() defind in helper function for logged in user detail
                    ->whereHas('itenary', function($query) {
                        $query->where('tour_id', '21'); }) <-- pass tour id
                    ->whereHas('inclusion', function($query) {
                        $query->where('tour_id', '21'); }) <-- pass tour id
                    ->first();

【问题讨论】:

    标签: php laravel-5 foreign-keys


    【解决方案1】:

    你不能在 Laravel 上做这样的事情,因为关系是Has Many

    你应该这样做:

    $tour = Tour::where('slug', $slug)
    ->whereHas('user',  function($query) {
        $query->where('user_id', user()->id);
    }) <-- user() defind in helper function for logged in user detail
    ->whereHas('itenary', function($query) {
        $query->where('tour_id', '21');
    }) <-- pass tour id
    ->whereHas('inclusion', function($query) {
        $query->where('tour_id', '21');
    }) <-- pass tour id
    ->first();
    
    $images = $tour->image;
    $inclusions = $tour->inclusion;
    $exclusions = $tour->exclusion;
    $highlights = $tour->highlight;
    $itenaries = $tour->itenary;
    

    【讨论】:

      猜你喜欢
      • 2017-09-21
      • 2014-11-29
      • 2014-01-11
      • 2016-09-11
      • 2018-10-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多