这很奇怪,我不知道我做错了什么。 我有2个型号:
class Project extends Eloquent {
public function status()
{
return $this->belongsTo('ProjectStatus','status_id');
}
}
和
class ProjectStatus extends Eloquent {
protected $table = 'PStatus';
public function projects()
{
return $this->hasMany('Project');
}
}
表“projects”具有正确的外键:
Schema::create('PStatus', function($table) {
$table->increments('id');
$table->string('name', 64);
$table->unique('name');
});
Schema::create('Projects', function($table) {
$table->increments('id');
$table->string('name', 100);
$table->integer('status_id')->unsigned();
$table->foreign('status_id')->references('id')
->on('PStatus')
->onDelete('cascade');
});
在数据库中(例如)我只有一个项目:“Project_1”(id = 1),status_id = 1(让我们说状态名称=“打开”)。如果我执行以下查询:
$projects = Project::with(array('status' => function($query){
$query->where('name', '<>', 'Open');
}))->get();
我仍然在结果中获得该项目!!这是sql日志:
array (size=3)
'query' => string 'select * from `PStatus` where `PStatus`.`id` in (?) and `name` <> ?' (length=67)
'bindings' =>
array (size=2)
0 => int 1
1 => string 'Open' (length=4)
'time' => float 0.36
如果我打印:
var_dump($projects->count());
我还有1个项目!怎么会?
我可以通过将查询更改为:
$projects = Project::where('status_id', '<>', 1)->get(); //assuming that status_id=1 => "Open"
但我不想直接使用ID,因为我认为方法 应该有效。我在这里做错了什么???
答案 0 :(得分:0)
实际上这就是答案: Eloquent Nested Relation with Some Constraint
与 with 方法存在巨大混淆。我应该使用加入。