relationship array null when eager loading in laravel - php

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');
}
}

Related

AngularJS & Laravel 4.2 retrieving data from multip tables and joining them

I've recently started to work with Laravel and I just recently got help to insert the data into multiple tables from one controller. Now I'm trying to retrieve data from the database and populate the form if an edit is needed or if someone needs to look at the data to be able to confirm it is correct. I don't understand how I join the tables is this in the model in Laravel? Or do I have to create a join SQL query?
Travelbill.php Model
<?php
class Travelbill extends Eloquent {
protected $table = 'travelbill';
protected $primaryKey = 'TravelbillId';
protected $fillable = array('ResourceId', 'Destination', 'StartDay', 'StartTime', 'EndDay', 'EndTime', 'Invoice', 'TravelCompensation');
public $timestamps = true;
public function travelbill() {
return $this->belongsTo('User', 'ResourceId', 'ResourceId');
}
public function cost() {
return $this->hasOne('Cost', 'TravelbillId', 'TravelbillId');
}
public function allowance() {
return $this->hasOne('Allowance', 'TravelbillId', 'TravelbillId');
}
}
?>
Cost.php Model
<?php
class Cost extends Eloquent {
protected $table = 'cost';
protected $primaryKey = 'CostId';
// protected $fillable = array('TravelbillId', 'Description', 'DescriptionByHiq', 'SekInklMoms', 'SekExklMoms', 'SekInklMomsByHiq', 'SekExklMomsByHiq', 'Currency', 'ExchangeRate');
protected $fillable = array('TravelbillId', 'Description', 'DescriptionByHiq', 'SekInklMoms', 'SekMoms', 'SekInklMomsByHiq', 'SekMomsByHiq', 'Currency', 'ExchangeRate');
public $timestamps = false;
public function cost() {
return $this->belongsTo('Travelbill', 'TravelbillId', 'TravelbillId');
}
}
?>
Allowance.php Model
<?php
class Allowance extends Eloquent {
protected $table = 'allowance';
protected $primaryKey = 'AllowanceId';
protected $fillable = array('TravelbillId', 'DayAllowance', 'Breakfast', 'Lunch', 'Dinner');
public $timestamps = false;
public function allowance() {
return $this->belongsTo('Travelbill', 'TravelbillId', 'TravelbillId');
}
}
?>
Or where am i doing this join so if i get the travelbill it also gets the Cost and Allowance data with the request?
EDIT:
I need to get the data into my AngularJS form so if a person with id = 1 needs to edit his Travelbill he should be able to click a edit button and see the information ha has filled out.
The simplest form of data retrieval you can do here is to do the following:
$travelBills = Travelbill::with(['code','allowance'])->get();
This is Eager Loading and will perform three queries:
Load all the travel bills
Load all codes that have foreign keys matching all the travelbill ids and assign them to each travel model
Do the same with allowances
What you'll have in the end that every Travelbill model will already have an associated Code and Allowance model, allowing you to work like:
echo $travelBill->cost->SekInklMoms;
for one of the Travelbills you loaded. Note a couple of things in the first query:
The travelbills are not filtered, we are loading them all at this point.
We are doing it simply, not necessarily efficiently. I recommend first get comfortable with the relationships loading before get onto things like joins (which break the spirit of Eloquent ORM in any case)

Laravel 5.4 Auth::User() with relationship not working

I have Table Vendors (for test Auth relationship) and Table Vendor_users,
But i use Auth::user() it not relationship
And This Database
In Vendor model
protected $table = 'vendor_users';
public function Vendor_test(){
return $this->belongsTo(Vendor_test::class);
}
And Vendor_test model
protected $table = 'vendors';
public function Vendor(){
return $this->hasMany(Vendor::class);
}
from chat and your current table structure, you should have relation like this
in Vendor Model
public function vendor_contact()
{
return $this->belongsTo(Vendor_contact::class, 'vendor_contact_id');
}
in Vendor_contact Model
protected $primaryKey = 'vendContactId'; //check this
public function vendor()
{
return $this->hasOne(Vendor::class, 'vendor_contact_id');
}
Now use lazy eager loading for loading vendor_contact relationship
Auth::user()->load('vendor_contact');
dd(Auth::user());
As per the discussion and the table structure you have,
Add the relation function in your model vendor_users.
protected $table = 'vendor_users';
public function vendor_contact()
{
return $this->belongsTo(Vendor_contact::class, 'vendor_contact_id');
}
get the user with the vendor_contact and check
$user = Auth::user()->with('vendor_contact')->first(); // As you asked with for auth
//OR
$user = Auth::user()->load('vendor_contact'); // From the rkj answer as I found this good.
// OR
$user = Vendor::find(1)->with('vendor_contact')->first();
dd($user);

Laravel Multiple linking column in another table with relationships?

I'm trying to create a league table in Laravel but I'm running into some issues with guess what, relationships, again. They never seem to work for me in Laravel. It's like they hate me.
I have a modal for matches
<?php
namespace App\Database;
use Illuminate\Database\Eloquent\Model;
class Match extends Model
{
protected $primaryKey = 'id';
protected $table = 'matches';
public $timestamps = false;
protected $guarded = ['id'];
}
And a modal for teams, but with a matches() function
<?php
namespace App\Database;
use Illuminate\Database\Eloquent\Model;
class Team extends Model
{
protected $primaryKey = 'id';
protected $table = 'teams';
public $timestamps = false;
protected $guarded = ['id'];
public function matches() {
return $this->hasMany('App\Database\Match', 'team_one_id, team_two_id');
}
}
I think the issue comes with team_one_id, team_two_id as the teams primary key could be in either one of them columns for the other table. When calling count() on matches() it throws an error.
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'matches.team_one_id, team_two_id' in 'where clause' (SQL: select count(*) as aggregate from matches where matches.team_one_id, team_two_id = 1 and matches.team_one_id, team_two_id is not null)
can you try this syntax
return $this->hasMany('modelPath', 'foreign_key', 'local_key');
Does Match table have a column maned 'team_id'?
because it's the default naming convention in the laravel docs for mapping the tables.
if you do have the column and populate the data you can just remove the foreign & local keys from matches() relationship. you don't need it. Laravel will automatically map it for you.
if you do not have the 'team_id' on Matches table please add the column and add the respective team ids for matches.
<?php
namespace App\Database;
use Illuminate\Database\Eloquent\Model;
class Team extends Model
{
protected $primaryKey = 'id';
protected $table = 'teams';
public $timestamps = false;
protected $guarded = ['id'];
public function matches() {
return $this->hasMany('App\Database\Match');
}
}
This way you can implement it, Add these relationship and a method in Team Model
public function homeMatches() {
return $this->hasMany('App\Database\Match', 'team_one_id');
}
public function awayMatches() {
return $this->hasMany('App\Database\Match', 'team_two_id');
}
public function matches() {
return $this->homeMatches->merge($this->awayMatches);
}
Now Fetch the data
$team = Team::find(1);
$matches = $team->matches(); //now it will fetch all matches for both columns
If you want to fetch matches as attributes then you can add one method
in your Team model
public function getMatchesAttribute()
{
return $this->homeMatches->merge($this->awayMatches);
}
Now you can fetch the matches as $matches = $team->matches;
Here is the difference
$team->matches returns Illuminate\Database\Eloquent\Collection
And
$team->matches() returns Illuminate\Database\Eloquent\Relations\{Relation Name}
You can't use matches in Eager loading like Team::with('matches') because matches is not a relationship and that causing your Error. What you can do is add homeMatches and awayMatches in eager loading and then call $team->matches().
$teams = Team::with('homeMatches', 'awayMatches')->get();
$teams->each(function ($team) {
print_r($team);
print_r($team->matches());
});

Laravel Eloquent nesting

I'm trying to return nested JSON response, need to connect multiple tables, but for now, I'm just trying with 3, the levels can go deeper. My models are following:
Update #1:
class Sport extends Eloquent {
protected $table = 'sportovi';
protected $fillable = ['id', 'sport_eng'];
public $timestamps = false;
public function liga(){
return $this->hasMany('League', 'sport_id');
}
}
class League extends Eloquent {
protected $table = 'lige';
protected $fillable = ['league_id', 'liga', 'sport_id'];
public $timestamps = true;
public function mec(){
return $this->hasMany('Match', 'match_id');
}
}
class Match extends Eloquent {
protected $table = 'mecevi';
protected $fillable = ['match_id', 'home', 'away', 'kotime', 'day', 'kolo', 'sport_id', 'league_id', 'date', 'long_id'];
public $timestamps = false;
public function liga(){
return $this->belongsTo('Match', 'league_id');
}
}
If I do:
$sportovi = Sport::with('liga')->get();
return $sportovi;
everything is normal, children of "lige" are nested where they should be, as shown on the link here, but, if I try to add the Match, like this:
$mecevi = Sport::with('liga.mec')->get();
I get a "mec" node, which is an empty array, as shown here, instead going one level deeper, like in the previous example.
I've also tried making multiple with() conditions which throws an error
Call to undefined method Illuminate\Database\Query\Builder::mec()
Update: Still the same, mec:[], empty array.
I'm using Laravel 4.2.
From my understanding, you want to get all the matches of leagues
The problem might be in the second parameter in hasMany function
public function mec(){
return $this->hasMany('Match', 'league_id');
}
The second parameter need to be foreign_key
public function mec(){
return $this->hasMany('Match', 'match_id', 'league_id');
}
source: http://laravel.com/docs/4.2/eloquent#one-to-many
Figured it out, my table relations were off, after giving all the conditions, like
return $this->hasMany('Comment', 'foreign_key', 'local_key'); everything started working as it should. Thanks everybody.

Laravel 4, how to access reverse one-to-many relation?

Code:
<?php
class Catering extends \Eloquent {
protected $table = 'catering';
public $timestamps = FALSE;
public function offers() {
return $this->hasMany('Offer', 'cid');
}
}
class Offer extends \Eloquent {
protected $table = 'catering_offer';
public $timestamps = FALSE;
public function catering() {
return $this->belongsTo('Catering');
}
}
I am able to do
$offers = Catering::find(1)->offers;
but, the inverse is not working:
$catering = Offer::find(1)->catering;
is always returning NULL. Database has the right values.
Offer table has 2 columns:
primary(id), int(cid)
that references catering.id.
The question:
How can i access the reverse side of this relation?
You said that, I am able to do
$offers = Catering::find(1)->offers;
and in your Catering model you have
public function offers() {
return $this->hasMany('Offer', 'cid');
}
It seems like you've defined a different foreign key here (cid) to use it instead of the default one that laravel basically supposed to use, so, to do the reverse relation you have to do the same thing in your Offer model's catering function
public function catering() {
return $this->belongsTo('Catering', 'cid');
}
In the Laravel Documentation, it says that, you may override the conventional foreign key by passing a second argument to the hasMany method, like
return $this->hasMany('Offer', 'custom_key');
Same way, to define the inverse of the relationship on the Offer model, you can use the belongsTo method, like
return $this->belongsTo('Catering', 'custom_key'); // cid

Categories