我在雄辩的模型上设置了一个访问器,运行得很好,但是对于我创建的模型的每个实例,关联的数据库查询只运行一次。在我的索引页上,这意味着5打查询。
<?php
class Thingy extends Model {
protected $appends = ["parentType"];
public function getParentTypeAttribute($value) {
return self::where("type"=>$this->type, "parent"=>1)->value("name");
}
}
class ThingyController extends Controller {
public function index() {
$thingys = Thingy::all();
return view("things.index", compact("thingys"));
}
}
我想减少数据库读取的次数,所以我尝试将其改为关系。我想这样我就可以利用迫不及待的装载。
<?php
class Thingy extends Model {
public function parent() {
return $this->hasOne("Thingy", "id")->where("type"=>$this->type, "parent"=>1);
}
}
class ThingyController extends Controller {
public function index() {
$thingys = Thingy::with(["parent"]);
return view("things.index", compact("thingys"));
}
}
问题是在关系方法中,
$this
是模型的空实例,与访问器中的不同,因此
$this->type
为空。
有没有一种方法可以从关系方法中访问我正在使用的模型的属性?