我有2个模特
class Computers extends Model
{
protected $fillable=['abn','vipnet_name','ip_address','serialnumber','zone_id','computer_model_id'];
public function zone()
{
return $this->belongsTo('App\Zone');
}
}
class Zone extends Model
{
protected $fillable=['name','parent_id','is_head'];
public function computers()
{
return $this->hasMany('App\Computers');
}
}
每台计算机都有一个区域(表[computers]中有一列[zone_id],它是表[zone]的外键)。
如果我想获得所有具有[zone]。[id] == 1或[zone]。[parent_id] == 1的Zone的计算机,我正在使用以下代码:
$c=Computers::all();
$res=[];
foreach ($c as $key => $value) {
if($value->zone->id==1 || $value->zone->parent_id==1)$res[]=$value;
}
return dd($res);
也许有一个更好的方法与ORM查询来做到这一点?
You can Query Relationship Existence to get only the computers where related Zone
id
value is1
or where related Zoneparent_id
value is1
: