简体   繁体   中英

Laravel hasOne relationship not loading

I'm trying to load a hasOne relationship in laravel with custom fields. This was built on top of an already defined database so i cant modify the database.

I have two tables both on sqlserver 2014 and on different schemas, all PK and FK are integers.

Tables:

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

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

Models:

CursoProgramado

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

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

Silabo

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

Controller, trying to get the relationship to work

$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...



Not really sure what is causing this

You need to define the belongs to relationship in the Silabo class


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

  public function cursoProgramado()
  {
     return $this->belongsTo(CursoProgramado::class, 'CursoProgramado', 'CursoProgramado')
  }
}

cheers

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM