Foreign key query laravel - the eloquent way

十年热恋 提交于 2019-12-12 03:55:30

问题


I am trying to find a way to write eloquent way to query my model.

I have a Form model every form belongs to a User (Form:User = 1:1). Each User has a State and a City associated with them. Admin reviews a Form and each admin can be assigned to multiple State and City.

I want to find the Form that belongs to an Admin.

This is the forms function in 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;

}

Currently it returns all the forms. Any help will be appreciated!!!


回答1:


You can try this:

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

return array_merge($citiesForms, $statesForms);

and you can look for hasManyThrough to make this done in one line



来源:https://stackoverflow.com/questions/40945634/foreign-key-query-laravel-the-eloquent-way

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!