2016-04-29 68 views
0

我有2个表用于获取laravel雄辩中的内部连接查询记录,但不能与联合数据获取一起使用。Laravel雄辩加入使用属于

表:类别

  1. ID
  2. cat_status

表:图像

  1. 标题
  2. 递减
  3. img_status

图像控制器

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

GET类别活跃,只有

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是不活动的。 任何想法如何加入状态条件。
在此先感谢。

+0

你属于方法应该我在模型不在控制器。 –

+0

对不起。我错误地添加了..在这里粘贴在控制器部分。属于条件是模型。 – shashik493

+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(); 
} 
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); 
    } 

再次谢谢大家:)。