Laravel - nested relationship shows null - php

I have a tw-tier nested hasOne relationship and the final relationship appears to be giving null values.
My JobApplication relationship has the following:
<?php
namespace App\Model;
use Illuminate\Database\Eloquent\Model;
class JobApplication extends Model
{
protected $table = 'job_applications';
protected $primaryKey = 'job_application_id';
public function jobrequest()
{
return $this->hasOne('App\Model\JobRequest', 'job_request_id', 'job_request_id');
}
}
My JobRequest Model has the following:
<?php
namespace App\Model;
use Illuminate\Database\Eloquent\Model;
class JobRequest extends Model
{
protected $table = 'job_requests';
protected $primaryKey = 'job_request_id';
public function jobgroup()
{
return $this->hasOne('App\Model\JobGroup', 'job_group_code', 'job_group_code');
}
public function jobapplication()
{
return $this->belongsTo('App\Model\JobApplication', 'job_request_id');
}
}
And my JobGroup has the following:
<?php
namespace App\Model;
use Carbon;
use Illuminate\Database\Eloquent\Model;
class JobGroup extends Model
{
protected $table = 'job_groups';
protected $primaryKey = 'job_group_code';
public function jobrequest()
{
return $this->belongsTo('App\Model\JobRequest', 'job_group_code');
}
}
I access them in my controller like so:
$job_applications = JobApplication::with(['jobrequest', 'jobrequest.jobgroup'])
->where('user_id', Auth::id())
->first();
It queries right on the Debugbar (and yes the query for job_groups gives out data), but when I dumped $job_applications, jobgroup shows null

Dont need to eager load it. I can access it like so
$job_applications = JobApplication::with('jobrequest')->where('user_id', Auth::id())->first();
dd($job_applications->jobrequest->jobgroup);

Related

Problem with Laravel Eloquent reltionships for tables without relations

I, ve got problem with eloquent relationships.
This is my DB
https://i.stack.imgur.com/2we4g.jpg
https://i.stack.imgur.com/20KeG.jpg
I've got Santander ID in santander column in partner table and want to use data from those two table like from one
This is my Partner.php model:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Partner extends Model
{
use HasFactory;
protected $table='partner';
protected $connection='mysql2';
protected $guarded = [];
public $primaryKey = 'id';
public function santander()
{
return $this->hasOne(Santander::class, 'id', 'santander');
}
}
This is my Santander.php model:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Santander extends Model
{
use HasFactory;
protected $table='santander';
protected $connection='mysql2';
protected $guarded = [];
public $primaryKey = 'id';
public function partner()
{
return $this->belongsTo(Partner::class, 'id', 'santander');
}
}
In controller I use Eloquent collection like this:
use App\Models\Partner;
use App\Models\Santander;
$partners = Partner::paginate(10);
In view. I am using it like this:
#foreach partners as partner
{{ $partner->santander->operator }}
#endforeach
but it generates error:
Trying to get property 'santander' of non-object
First of all are you sure about the relationships itself?
$this->hasOne(Santander::class, 'id', 'santander');
The first extra argument should be the foreign key, so assuming that the related column in the model Santander is named santander then it should be:
$this->hasOne(Santander::class, 'santander', 'id');
(the specified id as last param can be omitted btw)
Same goes for the relationship in the other model.

Appending an attribute to a Laravel 7.9.2 model?

Here is my code:
namespace App;
use Illuminate\Database\Eloquent\Model;
class Unit_Live extends Model
{
protected $table = 'live_data_units';
public function getUnitNameAttribute()
{
return "{$this->unitName}";
}
protected $appends = ['unit_name'];
}
Output:
If I change the $appends array, I can see default:
protected $appends = ['unit_name' => 'default'];
The expected output should be unit_a. unitName is a column in my table, value is shown under #attributes in image 1.
Docs:
https://laravel.com/docs/7.x/eloquent-serialization#appending-values-to-json

Specifying Relationship Fields in Eloquent Models using pivot tables on existing table schema

Whilst reading documentation on Laravel for pivot tables I have hard time guessing on how I can specify the appropriate field whilst moving/redesighning the php code of my current project into Laravel.
The problem that I have is that on my existing project I have the following tables:
ohimeSama:
id: Primary Key
namae: String
oujiSama
id: Primary Key
namae: String
suki:
id: pk
princess_id: Foreighn Key Ohimesama
prince_id: Foreighn Key Oujisama
For the Ohimesama table I set the following Model:
namespace App\Model;
use Illuminate\Database\Eloquent\Model;
use App\Model\Suki;
use App\Model\Oujisama;
class Ohimesama extends Model
{
public $timestamps = false;
protected $table = "ohimesama";
public function princesThatShesInLove()
{
return $this->belongsToMany(Oujisama::class)->using(Suki::class);
}
}
Same for the Oujisama:
namespace App\Model;
use Illuminate\Database\Eloquent\Model;
use App\Model\Ohimesama
use App\Model\Suki;
class Oujisama extends Model
{
public $timestamps = false;
protected $table = "ohimesama";
public function lovedByPrincess()
{
return $this->belongsToMany(Ohimesama::class)->using(Suki::class);
}
}
Also, the pivot Model for Suki is:
namespace App\Model;
use Illuminate\Database\Eloquent\Relations\Pivot;
class Suki extends Pivot
{
public $timestamps = false;
protected $table = "suki";
}
So I want to know how I can specify the appropriate relationship fields representing the foreign keys on table suki? In the documentation I find hard to figure out how these fields are being specified.
In order to solve the problem you need to follow these 2 major steps:
Specify the foreighn keys in the pivot model Suki via relationships:
namespace App\Model;
use Illuminate\Database\Eloquent\Relations\Pivot;
use App\Model\Oujisama;
use App\Model\Ohimesama;
class Suki extends Pivot
{
public $timestamps = false;
protected $table = "suki";
public function ohimesama()
{
return $this->belongsTo(Ohimesama::class, 'princess_id');
}
public function ohimesama()
{
return $this->belongsTo(Oujisama::class, 'prince_id');
}
}
Then on the relationship definition you specify the return pk of the model you want to return. Using the Pivot as fk resolver, In out case we will define our Ohimesama model:
namespace App\Model;
use Illuminate\Database\Eloquent\Model;
use App\Model\Suki;
use App\Model\Oujisama;
class Ohimesama extends Model
{
public $timestamps = false;
protected $table = "ohimesama";
public function princesThatShesInLove()
{
return $this->belongsToMany(Oujisama::class,'suki','id','id')->using(Suki::class);
}
}
If Oujisama had as pk oujisama_id instead of plain id, then the relationship definition would be:
return $this->belongsToMany(Oujisama::class,'suki,'id','oujisama_id')->using(Suki::class);
Similar, the OujiSama's relation is defined as well.

get data from model with condition laravel 5.7

I have Users_group model in my Laravel project.
Code:
<?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Database\Eloquent\Model;
class Users_group extends Model
{
use Notifiable;
protected $table = 'users_groups';
protected $fillable = ['id', 'user_id', 'group_id', 'created_at', 'updated_at'];
public function getGroupData()
{
return $this->hasOne('App\Group','id','group_id');
}
}
And when I want to get data from this model I use this my custom method:
$data = App\Users_group ::get();
It's working great
I want to get the data from model with condition not like this:
$data = App\Users_group::where('group_id','>',5)->get();
I need to put the condition inside the model file thats make the model return the data everytime I call User_group::get() return it when condition inside the model.
Thanks!
You can use query scopes to achieve this. Query scopes allow you to add a global constraint to a model.
In your case, you could add the following boot method to your model:
protected static function boot()
{
parent::boot();
static::addGlobalScope('groupOver5', function (Builder $builder) {
$builder->where('group_id', '>', 5);
});
}
try this one in by using scope in model
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Database\Eloquent\Model;
class Users_group extends Model
{
use Notifiable;
protected $table = 'users_groups';
protected $fillable = ['id', 'user_id', 'group_id', 'created_at', 'updated_at'];
public function scopeGetGroupData($query,$value,$opertor = '>')
{
return $query->where('group_id', $opertor, $value);
}
}
get data in controller like this u can pass also parameter in method
App\Users_group::GetGroupData($value)->get();

How to get data for one to many relationship using Eloquent in Laravel?

How to get data for one to many relationship using Eloquent in Laravel? Actually I followed Eloquent Documentation. But my code returns me an empty array. Here's my work:
Database Schema
Parent Table: mtg_workspace with columns (mw_id[primary key], mw_name,..., mw_access)
Child Table: mtg_workspace_amenities with columns (id[primary key], wa_mwid, wa_name)
Model: MtgWorkspace.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class MtgWorkspace extends Model
{
protected $table = 'mtg_workspace';
public $timestamps = false;
public function MtgWorkspaceAmenities(){
return $this->hasMany('App\MtgWorkspaceAmenities', 'wa_mwid');
}
}
Model: MtgWorkspaceAmenities.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class MtgWorkspaceAmenities extends Model
{
protected $table = 'mtg_workspace_amenities';
public $timestamps = false;
public function MtgWorkspace(){
return $this->belongsTo('App\MtgWorkspace');
}
}
Controller: WorkspaceController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\MtgWorkspace;
use App\MtgWorkspaceAmenities;
class WorkspaceController extends Controller
{
public function index()
{
$workspace = MtgWorkspace::with('MtgWorkspaceAmenities')->get();
return $workspace;
}
}
and here it shows following output:
Can you try defining the primary key for the MtgWorkspace model (as it is not id):
protected $primaryKey = 'mw_id';
I don't think it can match up the children MtgWorkspaceAmenities to the parent MtgWorkspace models as it is trying to use the id attribute on MtgWorkspace to match to the foreign key on MtgWorkspaceAmenities when it spins through the result of the eager loading.
Side Note:
You will have to pass more parameters to the inverse relationship on MtgWorkSpaceAmenities when defining it, as belongsTo() wants to use the calling methods name snake cased with _id added if not told otherwise as the key.

Categories