通过静态方法返回关系结果


Returning a relationships results through static method

我正试图在我的雄辩模型上提供一个额外的静态"find"方法,如下所示:

public static function findBySku($sku)
{
    // Using new self; provides the same empty collection results
    $instance = new static;
    // Using $instance->sku()->newQuery()->get() also returns the same empty collection
    $results = $instance->sku()->get();
    /*
    * This returns an empty collection, however there are records inside the 
    * relationship database table?
    */
    dd($results);
}

所以我可以使用:Inventory::findBySku($sku);

关系如下:

public function sku()
{
    return $this->hasOne('Stevebauman'Maintenance'Models'InventorySku', 'inventory_id', 'id');
}

我知道关系本身不是问题所在,因为这会从数据库表fine:中返回结果

Inventory::find(1)->sku()->get();

有人知道为什么这不起作用吗?

我知道这可能是因为我从静态实例调用了一个非静态方法,但为什么它会返回一个结果集合而不抛出错误呢?

谢谢!

等一下,想好了,抱歉!

显式关系具有访问相关模型实例的方法getRelated()。然后我可以调用我需要的方法,例如:

public static function findBySku($sku)
{
    $instance = new static;
    // Using the getRelated() method allows me to run queries on the related model
    $results = $instance->sku()->getRelated()->get();
    dd($results);
}

这只是一种奇怪的变通方法,因为你会认为访问关系本身会给你正确的查询。

我希望这能帮助将来的某个人!