Laravel Eloquent加入使用属于

时间:2016-04-29 05:43:37

标签: laravel eloquent

我在laravel eloquent中有2个用于获取内连接查询记录的表,但是没有使用组合数据获取。

表:类别

  1. ID
  2. 名称
  3. cat_status
  4. 表格:图片

    1. ID
    2. 标题
    3. 递减
    4. img_status
    5. 图像控制器

      //get all active images    
          ImageModel::where('status',true)->get();     
           public function getCategory() {
                  return $this->belongsTo('\App\Api\CategoryModel','cat_id');    
      

      仅限类别

      public function getActiveCategory() {
                  return $this->getCategory()->where('cat_status','=', 1);
              }
      

      我只需要获取哪个类别是活动的,仅限图像。

      if cat 1,2,3   3(is inactive)
      image table
      title=a1,cat_id=1,
      title=a2,cat_id=2,
      title=a3,cat_id=3
      

      现在我得到所有3张图片,我只需要前2张,因为cat_id 3处于非活动状态。     任何想法我如何加入状态条件     提前谢谢。

2 个答案:

答案 0 :(得分:0)

良好的关系方法不提供连接。你必须手动完成。 如果你想从活动类别中获取图像,那么你将不得不这样查询:

// method from image model
public function getImagesFromActiveCategory() {
    return $this->join('category')
        ->select('image.*')
        ->join('category', 'category.id', '=', 'image.cat_id')
        ->where('cat_status','=', 1)
        ->get();
}

答案 1 :(得分:0)

感谢您提供快速回复, 我尝试使用其他但现在使用belongsToMany方法解决了。 下面的函数提供来自DB的精确记录,它们与每个类别和图像表以及类别状态活动记录仅匹配。

#Image Controller
 $images=  ImageModel::where('status',true)->get();
  foreach($images as $img){
    #get data
    $onlyactiveCategoryImages=$img->getActiveCategory()->get();
  } 

#image Model

   #get category data
    public function getCategory() {
   return $this->belongsToMany('\App\Api\CategoryModel','images','id','cat_id');
    }

    #get category active only
       public function getActiveCategory() {
        return $this->getCategory()->where('cat_status','=', 1);
    }

再次感谢大家:)。