【发布时间】:2018-12-19 00:58:58
【问题描述】:
菜鸟问题。我正在从事一个涉及与一些遗留软件交互的项目,并且数据库与常规 Laravel 关系不兼容。
如果我在这样的构造函数中定义事物:
public function __construct(array $attributes = array())
{
parent::__construct($attributes);
$this->vatpercentage = $this->customer()->vatpercentage;
$this->vatcode = $this->customer()->vatcode;
$this->partrevision = $this->part()->revision;
$this->unitprice = $this->part()->unitprice;
}
public function part(){
return Part::findOrFail($this->partnum);
}
public function customer(){
$traderid = Order::where('id', $this->orderid)->value('traderid');
return Customer::where('id', $traderid)->where('tradertype', 'C')->first();
}
我需要在构造函数中多次引用customer()、part()等类似函数。每次我引用 $this->customer() 等时都会查询数据库,还是在我第一次引用它时缓存结果,然后用于所有其他时间?基本上我是否通过以这种方式编码而不是设置 $this->customer = $this->customer() 并获取诸如 $this->customer->example 之类的值来进行很多不必要的数据库调用?
【问题讨论】:
-
第一次在请求中使用它时会被缓存。因此,如果您加载一个页面,它将只运行一次查询。下一页加载,它将再次运行查询。
-
您可以安装Laravel Debugbar 以跟踪您在每个页面上运行的查询。
-
没有。你没有做任何事情来缓存结果。每次运行 customer() 时,它都会构建并执行一个新查询。