【问题标题】:Foreign key query laravel - the eloquent way外键查询 laravel - 雄辩的方式
【发布时间】:2017-04-18 03:45:41
【问题描述】:

我正在尝试找到一种方法来编写雄辩的方式来查询我的模型。

我有一个Form 模型,每个表单都属于User(表单:用户= 1:1)。每个User 都有一个State 和一个City 与之关联。 Admin 审查Form,每个管理员可以分配给多个StateCity

我想找到属于AdminForm

这是 Admin.php (Model) 中的表单函数

public function forms()
{  


        //cities
        $cities = $this->cities->pluck('name'); 
        //states
        $states = $this->states->pluck('name');


        //get all form from the user and states
        $forms = Form::whereHas('user',function ($query) use($cities,$states)
        {
          // find form from his states or cities
           $query->whereIn('state',$states)->orWhereIn('city',$cities);

        });
        return $forms;

}

目前它返回所有的形式。 任何帮助将不胜感激!!!

【问题讨论】:

    标签: php laravel laravel-query-builder


    【解决方案1】:

    你可以试试这个:

    $citiesForms =$this->cities->forms->toArray();
    $statesForms = $this->states->forms->toArray();
    
    return array_merge($citiesForms, $statesForms);
    

    您可以查找hasManyThrough 以在一行中完成此操作

    【讨论】:

    • 如果我在City 模型中定义了form 关系, $this->cities->forms 将起作用,即使我这样做了,我也必须在那里编写相同的查询。这又回到了这个问题!
    • 您应该使用hasManyThrough 来获取城市中的表单,基于该城市的用户。请参阅Docs
    猜你喜欢
    • 2021-10-02
    • 2018-01-26
    • 2021-07-23
    • 2020-08-11
    • 2017-11-11
    • 2023-04-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多