【问题标题】:How to retrieve only those records that do not have an associated record?如何只检索那些没有关联记录的记录?
【发布时间】:2016-04-09 13:17:31
【问题描述】:

我正在使用 CakePhp 3.x,我正在尝试根据关联数据过滤数据。 假设我有两个模型 UsersProfiles

Users Has-one Profile 和 Profiles 属于一个用户。

所以我想让那些没有个人资料的用户帮助我如何申请条件?

$this->Users->find('all',[
  'conditions'=>['Profile.id'=>Null]
])

我正在尝试这样,我发现它是错误的,然后我尝试使用包含但包含过滤关联数据而不是用户所以有没有办法让那些没有个人资料的用户?

【问题讨论】:

    标签: php cakephp associations cakephp-3.0 query-builder


    【解决方案1】:

    请参阅下面的链接:-

    http://book.cakephp.org/3.0/en/orm/retrieving-data-and-resultsets.html#using-notmatching

    基于关联数据的数据过滤分为三种类型。

    1 -> 匹配

    2 -> noMatching

    3 -> 见上面的链接

    匹配 此函数将过滤与指定关联相关的结果:现在是配置文件。

    $this->Users->find()->matching('Profiles') //This will get those user how have profile 
    

    无匹配

    matching() 的反面是 notMatching()。此函数将更改查询,以便过滤与指定关联无关的结果:

    $this->Users->find()->noMatching('Profiles') //This will get those user how have no profile
    

    【讨论】:

      【解决方案2】:

      你可以试试这样的:

      $query = $this->Users->find()
        ->contain([
          'Profiles' => function ($q) {
            return $q
              ->select(['id', 'name'])  // Your profile fields, say id, name etc.
              ->where(['Profiles.id' => NULL]);
         }
      ]);
      

      希望这会有所帮助。

      【讨论】:

      • 查看此链接book.cakephp.org/3.0/en/orm/… 并感谢您的帮助。
      • @MuhammadAsifSaleem 如果您阅读了该内容并可以回答您的问题,请通过将解决方案发布为实际答案来做到这一点 - 谢谢!
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-12-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多