dongliang1654 2016-06-23 10:10
浏览 30

在cakephp 3.2中两次相同的表模型关联

I have done model association in cake 3.2

Here i have done it for one id of same table .

I have tried to do it for other one ,but its not working at all

below is the flow.

This output i am getting

{
   "id": 1,
   "publisher_id": 133,
   "user_id": 118,
   "Publisher": {
       "id": 133,
        "name": "Sradha sradha"
    }

Here i want to bind the user id also ,which is belongs to that same user table

The output should come like this(I want to get like this below)

 {
     "id": 1,
     "publisher_id": 133,
     "user_id": 118,
     "Publisher": {
          "id": 133,
          "name": "Sradha sradha"
     }
     "Users": {
         "id": 118,
         "name": "Sradha anjo"
     }

Here both publisher_id and user_id are belongs to same user table .

$this->AdminRevenues->belongsTo('Users', [ 
    'className' => 'Users', 
    'foreignKey' => 'user_id', 
    'propertyName' => 'Users']);

$this->AdminRevenues->belongsTo('Users', [ 
   'className' => 'Publisher', 
   'foreignKey' => 'publisher_id', 
   'propertyName' => 'Publisher']);

$totalAdminRevenue = $this->AdminRevenues->find('all')
->contain([
     'Users' => ['queryBuilder' => function ($q) {
    return $q->select(['id', 'name']);
 }]])
 ->toArray();

Please suggest ,any suggestion will be highly appreciated.

  • 写回答

3条回答 默认 最新

  • 普通网友 2016-06-23 11:16
    关注

    Aliases must be unique

    What this is doing:

    $this->AdminRevenues->belongsTo('Users', [ 
        'className' => 'Users', 
        'foreignKey' => 'user_id', 
        'propertyName' => 'Users']);
    
    $this->AdminRevenues->belongsTo('Users', [ 
       'className' => 'Publisher', 
       'foreignKey' => 'publisher_id', 
       'propertyName' => 'Publisher']);
    

    Is declaring an association using AdminRevenues.user_id and then immediately overwriting with an association AdminRevenues.publisher_id. Effectively the first call to belongsTo isn't doing anything.

    Association aliases need to be unique, otherwise code such as $foo = $this->AdminRevenues->Users would be ambiguous. So, just make the association aliases unique:

    $this->AdminRevenues->belongsTo('Users', [ 
        'className' => 'Users', 
        'foreignKey' => 'user_id', 
        'propertyName' => 'Users']);
    
    $this->AdminRevenues->belongsTo('Publishers', [ // <--- 
       'className' => 'Users',                      // <---
       'foreignKey' => 'publisher_id', 
       'propertyName' => 'Publisher']);
    
    评论

报告相同问题?

悬赏问题

  • ¥15 关于#MATLAB#的问题,如何解决?(相关搜索:信噪比,系统容量)
  • ¥500 52810做蓝牙接受端
  • ¥15 基于PLC的三轴机械手程序
  • ¥15 多址通信方式的抗噪声性能和系统容量对比
  • ¥15 winform的chart曲线生成时有凸起
  • ¥15 msix packaging tool打包问题
  • ¥15 finalshell节点的搭建代码和那个端口代码教程
  • ¥15 Centos / PETSc / PETGEM
  • ¥15 centos7.9 IPv6端口telnet和端口监控问题
  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作