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
Related
I'm doing my first project with laravel 5.5 aç and now I'm establishing models and relationships
My project consists of a social network of video games.
The two models that I want to relate are the following, it would be a many-to-many relationship:
the genre of the game:
class Genero extends Model
{
protected $primaryKey = "cod";
public $incrementing = true;
protected $keyType = "int";
protected $table = "generos";
protected $fillable = ["cod","nombre"];
//public $timestamps = false;
public function juegos(){
return $this->belongsToMany('App\Juego',"juegosGeneros","codGenero","codJuego");
}
}
And the Game
class Juego extends Model
{
protected $primaryKey = "codJuego";
public $incrementing = false;
protected $keyType = "int";
protected $table = "juegos";
protected $fillable = ["cod", "nombre"];
//public $timestamps = false;
public function generos(){
return $this->belongsToMany('App\Genero',"juegosGeneros","codJuego","codGenero");
}
}
My db tables are that:
CREATE TABLE juegos(
cod INT AUTO_INCREMENT,
nombre VARCHAR(50),
PRIMARY KEY (cod)
);
CREATE TABLE generos(
cod INT AUTO_INCREMENT,
nombre VARCHAR(50),
PRIMARY KEY (cod)
);
CREATE TABLE juegosGeneros(
codJuego INT,
codGenero INT
);
My problem:
I have inserted data in the tables and when retrieving them
<?php
$juego = \App\Juego::where("cod","1")->first();
dd($juego->generos);
?>
they returned me an empty array
Collection {#188 ▼
#items: []
}
Observing the queries made to the database laravel do this:
select `generos`.*, `juegosGeneros`.`codJuego` as `pivot_codJuego`, `juegosGeneros`.`codGenero` as `pivot_codGenero`
from `generos`
inner join `juegosGeneros`
on `generos`.`cod` = `juegosGeneros`.`codGenero` where `juegosGeneros`.`codJuego` is null
Idont know the reason of this condition, and I think that is the problem
where `juegosGeneros`.`codJuego` is null
I really appreciate your help
You set the wrong primary key:
class Juego extends Model
{
protected $primaryKey = "cod";
}
I'm running Laravel 5.4 and for some reason I cannot do a column select on a 1-to-many polymorphic relation. I want to limit the columns returned in the related table.
Here's my '1 side' of my 1-to-many relationship:
class MapNodes extends Model {
protected $table = 'map_nodes';
protected $fillable = ['title'];
protected $validations = ['title' => 'max:200|string' ];
public function SystemConstants() {
return $this->morphMany('App\Modules\Models\SystemConstants', 'imageable');
}
}
Here's my 'many side' table in the relationship:
class SystemConstants extend Model {
protected $table = 'system_constants';
protected $fillable = ['name','imageable_id','imageable_type'];
protected $validations = ['name' => 'max:200|string',
'imageable_id' => 'integer|required',
'imageable_type' => 'max:45|string'];
// define this model as polymorphic
public function imageable() {
return $this->morphTo();
}
}
Here's two ways I'm trying to call it. One gets all the columns on SystemConstants, and the second I just want two columns:
$temp = MapNodes::with('SystemConstants')->find(25786);
$temp = MapNodes::with([ 'SystemConstants' =>
function( $query ) {
return $query->select('system_constants.id', 'system_constants.name' );
} ])->find(25786);
Why does the first call return the related records, but not the second? The below SQL statements for both calls look exactly the same (with the exception that I'm only wanting two columns in the second call).
select * from `system_constants` where
`system_constants`.`imageable_id` in (?) and
`system_constants`.`imageable_type` = ? - a:2:{i:0;i:25786;i:1;s:5:"Nodes";}
select `system_constants`.`id`, `system_constants`.`name` from `system_constants` where
`system_constants`.`imageable_id` in (?) and
`system_constants`.`imageable_type` = ? - a:2:{i:0;i:25786;i:1;s:5:"Nodes";}
In order to work you must add both the foreign key and primary key on the select statement:
$temp = MapNodes::with([ 'SystemConstants' =>
function( $query ) {
return $query->select('system_constants.id', 'system_constants.name', 'system_constants.imageable_id');
} ])->find(25786);
I am using Laravel 5.3 ad having issues on saving through the hasMany relationship.
I have tables job and jobsite which has One-to-Many Relation i.e Each jobsite has one or many jobs
but when I am trying to add job_job_site_id in the job table using associate() it send me an error:
SQLSTATE[42703]: Undefined column: 7 ERROR: column "job_site" of relation "job" does not exist
LINE 1: update "job" set "updated_at" = $1, "job_site" = $2 ...
^ (SQL: update "job" set "updated_at" = 2016-11-13 15:29:37, "job_site" = where "job_id" = 3)
SQLSTATE[42703]: Undefined column: 7 ERROR: column "job_site" of relation "job" does not exist
LINE 1: update "job" set "updated_at" = $1, "job_site" = $2 ...
^
Database structure:
job (1st table)
– job_id
– job_name
– job_job_site_id
- created_at
- updated_at
job_site (2nd table)
– job_site_id
– job_site_name
- created_at
- updated_at
Model Class Job:
class Job extends Model
{
protected $table = 'job';
protected $primaryKey = 'job_id';
public function jobsite() {
return $this->belongsTo('App\Models\JobSite', 'job_site', 'job_job_site_id', 'job_site_id');
}
}
Model Class JobSite:
class JobSite extends Model
{
protected $table = 'job_site';
protected $primaryKey = 'job_site_id';
public function jobs() {
return $this->hasMany('App\Models\Job', 'job', 'job_job_site_id', 'job_id');
}
}
Controller:
public function jobsiteJobs($data)
{
$jobsite = JobSite::find(3);
$job_id = array(1,2,3);
if (!empty($jobsite)) {
foreach ($job_id as $id) {
$job = Job::find($id);
$job->jobsite()->associate($jobsite);
$job->save();
}
return 'Added';
}
else {
return 'Not found';
}
}
Do I have my relationship defined incorrectly here?
Yes, your have defined relationships incorrectly. The correct version is following:
Model Class Job:
class Job extends Model
{
protected $table = 'job';
protected $primaryKey = 'job_id';
public function jobsite() {
return $this->belongsTo('App\Models\JobSite', 'job_job_site_id', 'job_site_id');
}
}
Model Class JobSite:
class JobSite extends Model
{
protected $table = 'job_site';
protected $primaryKey = 'job_site_id';
public function jobs() {
return $this->hasMany('App\Models\Job', 'job_job_site_id', 'job_site_id');
}
}
here is an example
Table Structure
Game
--id
--game
Posts
--id
--game_id
--post_text
class Posts extends Eloquent {
protected $primaryKey = 'id';
protected $table = 'posts';
public function games() {
return $this->hasOne('games','id');
}
}
class Games extends Eloquent {
protected $primaryKey = 'id';
protected $table = 'games';
public function posts() {
return $this->belongsTo('posts','game_id');
}
}
I need to get the game name of a certain post. How can I get it using eloquent?
here is my initial code
echo $post->games['game'];
but I get the wrong data.
The way it queries is this.
'query' => string 'select * from `games` where `games`.`id` = ? limit 1' (length=52)
'bindings' =>
array (size=1)
0 => int 5
Firstly Eloquent model names are not plural, so by default they should be Game and Post.
Secondly relationship return values must be changed. In hasOne and belongsTo you will need to use model class names like below. I also left out some optional code which is not required for the code to work.
class Post extends Eloquent {
public function game() {
return $this->hasOne('Game');
}
}
class Game extends Eloquent {
public function post() {
return $this->belongsTo('Post');
}
}
Now you can get the game name by $post->game->name
I am having issues getting the relationship array back when eager loading in laravel 4. for example:
controller:
foreach (Apps::with('extra')->get() as $app)
{
print_r($app->toArray());//returns array but my relationship array at the bottom says null
echo $app->extra; //this will show my relationship details
}
model:
class Apps extends Eloquent
{
protected $connection = 'mysql_2';
protected $table = 'apps';
public $timestamps = false;
protected $primaryKey = 'name';
public function host()
{
return $this->belongsTo('Hosts','name');
}
public function extra()
{
$this->primaryKey='app_ip';
return $this->hasone('Extra','ip');
}
//other functions below.......
}
class Extra extends Eloquent
{
protected $connection = 'mysql_3';
protected $table = 'extra';
public $timestamps = false;
protected $primaryKey = 'ip';
public function app(){
return $this->belongsTo('Apps', 'app_ip');
}
mysql:
My mysql tables were not created through laravel they were previously existent. the app_ip column in the Apps table relates to the ip column in the extra table. it is a 1 to 1 relationship and I have specified the primary key in the relationship function. I am getting relationships back so I know that it is working.
I am able to get relationship data back when I call the function directly, but it does not show the relationship data when I try and print the full array. The main goal is to be able to return both the relationship columns and the app columns in one response.
You need to do this:
$apps = Apps::all();
$apps->load('extra');
foreach ($apps as $app)
{
print_r($app->toArray()); // prints your relationship data as well
}
What you have should work and iterating through the collection or using ->load() to eager load shouldn't make a difference. Are you using the visible restriction on your models? If so you will need to include the relationships.
class Apps extends Eloquent {
protected $visible = array(
'id',
'name',
'created_at',
'extra', // Make the relationship 'visible'
);
public function extra()
{
return $this->hasMany('Extra');
}
}