我正在laravel 5.5
上构建一个小应用程序,我正在检索关系缺失的模型,如下所示:
$milestone = Milestone::where('unique_id', $request->id)
->whereDoesntHave('block')
->first();
这工作正常但是当我将milestone
变量转换为数组时,我得到了荒谬的结果,我试过了:
$milestone = Milestone::where('unique_id', $request->id)
->whereDoesntHave('block', function ($q) use($request){
foreach($request->milestone as $m)
$q->where('unique_id', $m);
})
->first();
修改
以下是我的关系:
里程碑型号:
public function block()
{
return $this->morphMany('App\Models\Team\Block', 'block');
}
阻止型号:
public function block()
{
return $this->morphTo();
}
和我的块数据库表:
Schema::create('blocks', function (Blueprint $table) {
$table->increments('id');
$table->string('unique_id');
$table->string('block_type');
$table->integer('block_id');
$table->integer('generic_id');
$table->string('type');
$table->integer('user_id');
$table->timestamps();
$table->softDeletes();
});
在此帮助我,谢谢
答案 0 :(得分:0)
您应该使用whereIn
而不是foreach
多个where
子句。即
$q->whereIn('unique_id', $mArray);
如果将where
条款链接在一起,那些就是AND where
条款。作为一个例子
App\Models\User::where('id', 1)->where('id', 2)->toSql();
"select * from `users` where `id` = ? and `id` = ?"
App\Models\User::whereIn('id', [1,2])->toSql();
"select * from `users` where `id` in (?, ?)"
前者没有给出结果,而后者给出你可能期望的结果
答案 1 :(得分:0)
链whereDoesntHave()
:
$milestone = Milestone::where('unique_id', $request->id);
foreach($request->milestone as $m) {
$milestone = $milestone->whereDoesntHave('block', function ($q) use($m) {
$q->where('unique_id', $m);
});
}
$milestone = $milestone->first();
或者whereHas()
使用whereNotIn()
:
$milestone = Milestone::where('unique_id', $request->id)
->whereHas('block', function ($q) use($request) {
$q->whereNotIn('unique_id', $request->milestone);
})
->first();