对null调用成员函数get(),如何解析



如何编写一个函数来检查一列是否设置为50?

如果是50,则不可更新。。。

foreach ($orders as $order) 
{
// Gets updatable status
$updatable = $this->updateable($order->id);
// Saves new externals (create), if updateable
if ($updatable != false) 
{
$this->create();
}
}
<?php
namespace AppTraits;
use AppExternal;
trait Updateable
{
// If external status is not 50, it is updateable
public function updateable($id) {
// If External status is 50, it is not updateable
$externalStatus = External::find($id)->get('status');
if($externalStatus == 50) {
return $updateable = false;
}
}
}

我可以将其更改为findOrFail,但如何捕捉错误?

只需检查这个&尝试

<?php
namespace AppTraits;
use AppExternal;
trait Updateable
{
// If external status is not 50, it is updateable
public function updateable($id) {
// If External status is 50, it is not updateable
$externalStatus = External::find($id);
if($externalStatus->status == 50) {
return $updateable = false;
}
}
}

您可以这样做(以减少代码(。

public function updateable($id) {
// If External status is 50, it is not updateable
return External::where('id',$id)->where('status', 50)->first(); //or you could return ! Extenal... and omit ! in if.
}

如果数据不为空,first()将返回数据,与true类似。如果为空,则返回null,相当于false。所以在foreach中你可以做:

foreach ($orders as $order) 
{
// Saves new externals (create), if updateable
if ( ! $this->updateable($order->id) ) {
$this->create();
}
}

关于使用findOrFail捕获错误的问题,您可以使用try..catch()捕获ModelNotFoundException

我想您希望在正确的条件下从该方法返回true,而不仅仅是falsevoid/null,尽管我不确定您希望如何处理不存在的模型:

namespace AppTraits;
use AppExternal;
trait Updateable
{
public function updateable($id)
{
if (! ($external = External::find($id)) {
return false; // model not found
}
return $external->status != 50;
}
}

然后你的循环:

foreach ($orders as $order) {
if ($this->updateable($order->id)) {
$this->create();
}
}

最新更新