在Laravel中使用自定义查询返回模型

时间:2017-05-24 17:03:10

标签: laravel eloquent laravel-eloquent

我已经在我雄辩的模型中定义了自定义查询,并且我想知道在获得模型时包含其结果的最佳方式是什么。

我知道有受保护的$ with,但只接受关系然后有$ appends但是属性和我的查询返回整个对象而我不知道它是否是个好主意将其作为属性包含在内。

另外,如果在模型方法中有办法做到这一点,我想听听它,因为我不一定需要在每个模型实例上都有这些信息。

期待听到您的建议。

修改 我熟悉$ with和关系。 我要问的是我如何得到这样的东西来加载:

public function thisIsMyQuery()
{
    return DB::table('example')->where('const', '>', 3);
}

1 个答案:

答案 0 :(得分:0)

如果我理解了你的需要,你只想急切加载一个关系。为此,您必须在模型中定义关系,并在$with数组中添加方法的名称。

示例:

// Inside your model class

class Post extends Model
{
    protected $with = ['comments'];

    public function comments()
    {
        return $this->hasMany(Comment::class);
    }
}

// Usage

$post = Post::find(1)
$post->comments; // here are the related comments  
相关问题