【问题标题】:Laravel hasOne relationship not loadingLaravel hasOne 关系未加载
【发布时间】:2020-04-09 05:14:11
【问题描述】:

我正在尝试在 laravel 中使用自定义字段加载 hasOne 关系。这是建立在一个已经定义的数据库之上的,所以我不能修改数据库。

我在 sqlserver 2014 和不同架构上都有两个表,所有 PK 和 FK 都是整数。

表格:

表 CursoProgramado (schema dbo): CursoProgramado(PK) fieldA fieldB

表 silabos (schema sga): id(PK) fieldC fieldD CursoProgramado(FK)

型号:

CursoProgramado

class CursoProgramado extends Model {
  protected $connection = 'sqlsrv';
  protected $table = 'CursoProgramado';
  protected $primaryKey = 'CursoProgramado';

   public function silabo()
     {
        return $this->hasOne(Silabo::class, 'CursoProgramado', 'CursoProgramado');
     }
}

锡拉博

class Silabo extends Model {
  protected $connection = 'sqlsrv';
  protected $table = 'sga.silabos';
}

控制器,试图让关系发挥作用

$carga = CursoProgramado::findOrFail($carga);
//this return the model correctly
$carga->silabo;
//this should return the related model but returns NULL

// if i get the query log
DB::connection('sqlsrv')->enableQueryLog();
$carga->silabo;
dd(DB::connection('sqlsrv')->getQueryLog());

// i get this

array:1 [▼
  0 => array:3 [▼
    "query" => "select top 1 * from [sga].[silabos] where [sga].[silabos].[CursoProgramado] = ? and [sga].[silabos].[CursoProgramado] is not null"
    "bindings" => array:1 [▼
      0 => 147689
    ]
    "time" => 18.59
  ]
]
//Runnig query
select top 1 * from [sga].[silabos] where [sga].[silabos].[CursoProgramado] = 147689 and [sga].[silabos].[CursoProgramado] is not null;

// it return data
id  CursoProgramado consejeria
1933    147689   La consejería y orientación...



不确定是什么原因造成的

【问题讨论】:

    标签: php laravel eloquent eloquent-relationship


    【解决方案1】:

    需要在Silabo类中定义属于关系

    
    class Silabo extends Model {
      protected $connection = 'sqlsrv';
      protected $table = 'sga.silabos';
    
      public function cursoProgramado()
      {
         return $this->belongsTo(CursoProgramado::class, 'CursoProgramado', 'CursoProgramado')
      }
    }
    
    

    干杯

    【讨论】:

    • 它已定义,我只是没有包含它,因为我只是想从 CursoProgramado 模型中获取它,而不是相反。顺便说一句,当我这样做时它会起作用,问题就是这样 $carga = CursoProgramado::findOrFail($carga); $carga->silabo;
    • 您是否设置了架构?因为它在你的类定义中也被省略了
    • 您的意思是在 CursoProgramado 中吗?不,我不是因为连接默认为该架构,并且它正在我的其他模型上运行
    • 不,我的意思是在 Silabo。我假设您为每个模式使用不同的连接,但我猜您没有。使用不同的连接并尝试。仅供参考,在同一个应用程序中使用不同的模式不是一个好主意 IMO,更好的方法是使用微服务
    • 不幸的是,这就是我获得数据库的方式,而这个项目要求我使用该数据库和定义的模型或重新编写所有模型:/。只是尝试了不同的连接仍然没有运气。现在我只是要手动找到相关的模型,然后我猜。真正奇怪的是类似的关系正在起作用,所以也许是表定义?以前从未真正遇到过这个问题
    猜你喜欢
    • 2020-01-18
    • 2020-10-06
    • 2018-05-29
    • 2017-04-21
    • 2016-03-17
    • 1970-01-01
    • 2018-05-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多