laravel - 错误与wherehas和关系

时间:2014-04-23 14:23:23

标签: php laravel laravel-4 relationship

类别有自我关系。

这是我的高级搜索代码:

        $allcats = array();
    if(in_array('1',$category) OR in_array('2',$category) OR in_array('3',$category)) {
        foreach($category as $c) {
            foreach(Category::where('parentid',$c)->get()->toArray() as $cat) {
                $allcats[] = $cat['id'];
            }
        }
    } else {
        $allcats = $category;
    }

    $query->whereHas('categories', function($q) use($allcats)
    {
        $q->whereIn('category.id', $allcats);
    });  

我想要做的是,从三只主要猫中获取所有的儿童类别(我认为这样做很好)。然后,在数组中获取EACH类别的所有相关配方,在这里:

        $query->whereHas('categories', function($q) use($allcats)
    {
        $q->whereIn('category.id', $allcats);
    });    

这不起作用。不知怎的,我总是得到4个结果而不是10个(全部)! 我究竟做错了什么? $allcats看起来像这样:

[
"6",
"7",
"5",
"9",
"12",
"13",
"14",
"17",
"18",
"19",
"20",
"21",
"24",
"25",
"26"

]

对我来说也很好。
有任何想法吗?谢谢!

编辑#1:

    <?php

class Recipe extends Eloquent {

    /**
     * The database table used by the model.
     *
     * @var string
     */
    protected $table = 'recipes';

    public function categories() {
            return $this->belongsToMany('Category','category_recipe');
    }

和类别:

    <?php

class Category extends Eloquent {

    /**
     * The database table used by the model.
     *
     * @var string
     */
    protected $table = 'category';

    public function recipes() {
        return $this->belongsToMany('Recipe');
    }

    public function parent_category() {
        return $this->belongsTo('Category','parentid');
    }

    public function child_categories() {
        return $this->hasMany('Category','parentid');
    }

0 个答案:

没有答案