【问题标题】:Create conditional in Model methods在模型方法中创建条件
【发布时间】:2018-06-14 15:39:29
【问题描述】:

大家好,我希望在我的类别模型上创建一个自定义方法,但我需要用它创建一些条件。

table post:
- id;
- category_id
-name...


table Category:
- id
- parent_id
- name

假设我有一个帖子,在这个帖子中有一个名为 SomeSubcategoryName 的类别,我的帖子表中有一个名为 category_id 的列。

当我调用 post 记录时,我与类别模型有关系,但我希望在我的类别模型中有一个名为 masterCategory 的方法,在该方法中,我通过检查 parent_id 是否为空来给出 mster 类别,以防万一记录的 parent_id 为 null 很好,我返回记录,但如果不是,我需要使用 parent_id 值并在模型类别列 id 上搜索记录并返回结果。

想象一下这个场景:

$post = Post::find(2);

//这个调用应该返回主类别而不是子类别信息。

$post->masterCategory();

【问题讨论】:

    标签: php laravel laravel-5 eloquent


    【解决方案1】:

    在您的类别模型中定义其自身的关系:

    public function masterCategory()
    {
        return $this->belongsTo(App\Category::class, 'parent_id', 'id');
    }
    

    当您查询时,渴望在您的Post 上加载关系:

    $post = Post::with(['category', 'category.masterCategory'])->firstOrFail($id);
    

    像这样访问它:

    $post->category->masterCategory; // will be the mastery category or null
    

    否则我们:

    $post->category;
    

    不要过于复杂。

    【讨论】:

    • 我认为足够了: $post = Post::with('category.masterCategory')->firstOrFail($id);它已经将类别和 masterCategory 融合在一起了
    【解决方案2】:

    在您的类别模型中,您应该有这样的东西

    public function master()
    {
        return $this->belongsTo(Category::class, 'parent_id');
    }
    
    public function isMaster()
    {
        if($this->parent_id)
            return false;
        else
            return true;
    }
    

    现在您可以检查帖子的类别是否是主类别:

    if($post->category->isMaster())
        ....
    

    第二种方法是使用关系和雄辩

    $post = Post::with(['category', 'category.master'])->first($id);
    

    【讨论】:

    • 这个想法比使用 eaguear 加载要好,因为我想防止在 foreach 循环中发出请求以进行 category->isMaster 验证。
    • 我认为足够了: $post = Post::with('category.masterCategory')->firstOrFail($id);它已经将类别和 masterCategory 融合在一起了
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-17
    • 2012-03-22
    • 1970-01-01
    • 1970-01-01
    • 2016-07-19
    相关资源
    最近更新 更多