如何在模型中加载集合,然后使用查询构建器进行查询

时间:2017-06-16 03:46:50

标签: laravel laravel-5

我为评级创建了一个morphMany关系,我在使用model-> load或model :: with方法加载模型中的评级关系数据时遇到问题,两者都不允许我使用这些集合模型建设者。

如果我在模型的方法中执行此操作,则会抛出错误:

port

我需要评级查询构建器,以便我可以查询和过滤结果,但它不使用查询构建器,即使我将其作为范围,它仍然会引发相同的错误。

所有代码:

$all = this->ratings()->get(); 
return $all;
Call to undefined method Illuminate\Database\Query\Builder::ratingInfo()

1 个答案:

答案 0 :(得分:0)

以电话号码,用户和公司为例:

class PhoneNumber extends Model
{
    /**
     * Get all of the owning callable models.
     */
    public function callable()
    {
        return $this->morphTo();
    }
}
class Company extends Model
{
    /**
     * Get all of the model's phone numbers.
     *
     * @return mixed
     */
    public function phoneNumbers()
    {
        return $this->morphMany(PhoneNumber::class, 'callable');
    }
}

class User extends Model
{
    /**
     * Get all of the model's phone numbers.
     *
     * @return mixed
     */
    public function phoneNumbers()
    {
        return $this->morphMany(PhoneNumber::class, 'callable');
    }
}

将电话号码保存到用户或公司将是这样的:

$phoneNumber = new PhoneNumber(['number' => '555-555-5555']);
$user->phoneNumbers()->save(phoneNumber);

$phoneNumber = new PhoneNumber(['number' => '555-555-5555']);
$company->phoneNumbers()->save(new PhoneNumber(phoneNumber));

然后访问与每个相关联的电话号码集合,只需:

$user->phoneNumbers  // this is a Collection
$company->phoneNumbers  // this is a Collection

$user->phoneNumbers->count() // access to all Collection methods as this point