【问题标题】:Laravel - get rows not in custom hasMany relationshipLaravel - 获取不在自定义 hasMany 关系中的行
【发布时间】:2017-04-28 00:50:31
【问题描述】:

我有一个 admin 表,admin 有很多 form。每个form 都分配给他们仪表板上显示的admin

问题是form 可能没有分配给任何admin

我想得到所有这些forms 任何帮助表示赞赏。谢谢!

编辑:Adminform 通过自定义关系相关,如 Here 所述

总结一下,

Admin.php

public function states(){
    return $this->belongsToMany('App\State');
}

public function cities()
{
    return $this->belongsToMany('App\City');
}

//gets the forms in  this admin's city or state
//Let me know if there is a better way to do this, i feel like im overdoing stuff here 
public function forms()
{  
        //cities
        $cities = $this->cities->pluck('name'); 
        //states
        $states = $this->states->pluck('name');

        $users =  User::whereIn('state',$states)>orWhereIn('city',$cities)->get()->pluck('id');

        $forms = Form::whereIn('user_id',$users);

        return $forms;

}

我想获取不属于任何admin的表单

【问题讨论】:

  • 您基本上必须在表单模型上定义该关系的逆向。
  • 我已经添加了代码,你能指出我正确的方向吗?

标签: php laravel laravel-query-builder


【解决方案1】:

您可能正在寻找doesntHave

$forms=Form::doesntHave('admin')->get();

【讨论】:

  • 感谢您对此进行调查。其实关系不是一个标准有很多关系。我已编辑问题以更好地描述情况。
【解决方案2】:

你为什么不简单地做相反的事情呢?

$forms = Form::whereNotIn('user_id', $users);

【讨论】:

    猜你喜欢
    • 2018-06-12
    • 2015-11-29
    • 2020-04-29
    • 2014-10-29
    • 1970-01-01
    • 2023-03-31
    • 1970-01-01
    • 2020-11-15
    • 2017-12-19
    相关资源
    最近更新 更多