如何将参数传递给Laravel中的whereHas()子句

时间:2019-07-08 04:14:34

标签: laravel laravel-5 eloquent

我查询了类别模型以获取其中 const initialState = { userChoice: null, userScore: 0, cpuChoice: null, cpuScore: 0 } const [gameItems, dispatch] = useReducer((state, action) => { switch (action.type) { case "UPDATE_CHOICES": return { ...state, userChoice: action.userChoice, cpuChoice: action.cpuChoice }; case 'UPDATE_CPU_SCORE': return { ...state, cpuScore: state.cpuScore + 1 } default: return state; } }, initialState); const setChoices = (userChoice, cpuChoice) => { dispatch({ type: 'UPDATE_CHOICES', userChoice, cpuChoice }); }; const cpuScore = () => { dispatch({ type: 'UPDATE_CPU_SCORE'}) }; 用于查询Post模型的所有ID,但出现错误。

'name', '=', $name

这是我的错误。

  

Builder.php 877行中的ErrorException:compact():未定义的变量:   运算符

2 个答案:

答案 0 :(得分:0)

如果您设置的全部与我相同,那么一切都会很好!

职位与类别之间的关系表为ManyMany。因此,您需要一个数据透视表名称category_post来包含2个表的数据关系:

Schema::create('category_post', function (Blueprint $table) {
    $table->bigIncrements('id');
    $table->timestamps();
    $table->bigInteger('category_id')->unsigned();
    $table->foreign('category_id')->references('id')->on('categories')->onDelete('cascade');
    $table->bigInteger('post_id')->unsigned();
    $table->foreign('post_id')->references('id')->on('posts')->onDelete('cascade');
});

在Post模型中:

class Post extends Model
{
    public function categories(){
        return $this->belongsToMany(Category::class,'category_post','post_id','category_id');
    }
}

类别模型:

class Category extends Model
{
    public function posts(){
        return $this->belongsToMany(Category::class,'category_post','category_id','post_id');
    }
}

和YourController:

public function getList($name)
{
    $category_id = Category::where('name', '=', $name)->first()->id;

    $posts = Post::whereHas('categories', function ($q) use ($category_id) {
        $q->where('category_id', '=', $category_id);
    })->paginate(12);

    return view('show')->withPosts($posts)->withName($name);
}

祝您编程愉快!问我是否需要!

答案 1 :(得分:0)

如果你还在找这个

$posts = Post::whereHas('category', function (Builder $q) use ($category_id) {
    $q->where('id', '=', $category_id);
})->paginate(12);