Load Eloquent Model Relationships Child Nodes in Laravel 5.1 - php

I can't return $parent->child() | I get null;
Parent Model
class PrinterSetting extends Model
{
protected $table = 'printer_settings';
//fillables here
protected $with = ['copies'];
public function copies(){
return $this->hasMany(\App\DB\PrinterCopy\PrinterCopy::class, 'printer_id');
}
}
Child Model
class PrinterCopy extends Model
{
protected $table = 'printer_copies';
public function printer(){
return $this->belongsTo(\App\DB\PrinterSetting\PrinterSetting::class, 'id', 'printer_id');
}
}
Code in Controller:
$availablePrinters = $this->printerSetting->where('is_active', 1)->get();
foreach($availablePrinters as $availablePrinter)
{
//working
foreach($availablePrinter->copies() as $copy)
{
//Not working
}
}
I can't find the reason why it's not working.
I Tried to dump $availablePrinter->copies and it work, but ofcourse I can't insert it on foreach() loop.
Please help.

$availablePrinter->copies() return Query builder, you have to use $availablePrinter->copies which is Collection that you can add in loop, Try this
$availablePrinters = $this->printerSetting->where('is_active', 1)->get();
foreach($availablePrinters as $availablePrinter)
{
//working
foreach($availablePrinter->copies as $copy)
{
dd($copy)
}
}
Side note, also fix your belongsTo relation in PrinterCopy model, it should be like this
public function printer(){
return $this->belongsTo(\App\DB\PrinterSetting\PrinterSetting::class,'printer_id');
}

Related

Laravel - Model Eloquent without relationships

i trying to load all rows from a model without the relationship.
The attributes $with it not event set on my Event model but when i do
$events = Event::all();
all my relationship are loaded, and i can see all the query with the dbquerylog.
i don't understand why theses relationship are loaded,
Please help me !
Thanks you.
I'm using Laravel 8.
here's an example.
class Event extends Model {
public function items() {
return $this->hasMany(Item::class);
}
public function items2() {
return $this->hasMany(Item2::class);
}
public function items3() {
return $this->hasMany(Item3::class);
}
public function items4() {
return $this->hasOne(Item4::class);
}
}
$events = Event::all();
If you have a single instance of a model object, you can do:
$obj->withoutRelations();
As laravel documentations says you can use without: https://laravel.com/docs/8.x/eloquent-relationships
Model
protected $with = ['item1','item2','item3','item4'];
Controller
$events = Event::without(['item1','item2','item3','item4'])->get();
I met this problem one day, and it turned out that I was using relation in scope method. Because of this relation values were added to response.
Check out this example:
class Event extends Model {
public function items() {
return $this->hasMany(Item::class);
}
[...]
public function scopeItemsGreen() {
return $this->items->every(function ($item) {
return $item->color == 'green';
});
}

Laravel Polymorphic Relations returns NULL

I've read many posts about this issue but none of them works for me. I have a 'ISA' relationship in my database. A person can be either a Patient or a Nurse:
class Person extends Model
{
protected $table = 'persons';
public function commentable()
{
return $this->morphTo();
}
}
class Patient extends Model
{
public function persons()
{
return $this->morphMany('App\Person', 'commentable');
}
}
class Nurse extends Model
{
public function persons()
{
return $this->morphMany('App\Person', 'commentable');
}
}
This is my tables and the data inside them:
And this is my Route:
Route::get('person', function () {
$person = Person::find(1)->commentable();
return json_decode(json_encode($person), true);
});
I get an empty array!
You have to access the relationship as a property:
$person = Person::find(1)->commentable;

How to apply relationship with two id's in laravel

So I have a model called data_storage and another model entity_states
I have to fetch the record from data_storage with entity_states where entity_state has data_storage_id and state_id.
How can I use eloquent to achieve this ?.
Or Ill have to use Query builder and use innerJoin?
Update1
My Actual Query
$this->values['new_leads'] = $data_storages->with('actions','states','sla')->where('wf_id',$wfid)->get();
My data_storage modal
class data_storages extends Model
{
//
protected $fillable = ['layout_id','member_id','company_id','team_id','data','status','wf_id'];
function actions()
{
return $this->hasMany('App\Models\ActionDataMaps', 'data_id', 'id' );
}
function states()
{
return $this->hasOne('App\Models\workflow_states','id','status');
}
function sla()
{
//Here I have to get those row from entity_states model where , data_storage_id and state_id
}
}
Thanks
Here's the more reasonable way to do it:
class DataStorage extends Model {
public states() {
return $this->belongsToMany(State::class,"entity_states");
}
}
class State extends Model {
public storages() {
return $this->belongsToMany(DataStorage::class,"entity_states");
}
}
Then you can eager-load related models via e.g.:
$storage = DataStorage::with("states")->first();
$storage->states->first()->column_in_related_state;
Or via the state:
$state = State::with("storages")->first();
$state->storages->first()->column_in_related_storage;
If there are additional columns in the pivot table entity_states then you can refer to them in the relationship as e.g.:
public states() {
return $this->belongsToMany(State::class)->withPivot("pivot_column");
}
In your model data_storage you can define a property / method entity_states to get them:
class data_storage extends Model
{
public function entity_states()
{
return $this->hasMany('App\entity_states','data_storage_id')->where('state_id ','=',$this->table());
}
}
Then you can access them in an instance by
$entityStatesOfDataStorage = $yourDataStorageInstance->entity_states;
See this link:
https://laravel.com/docs/5.3/eloquent-relationships
for Query Builder you may use this:
DB::table('data_storage')
->join('entity_states','data_storage.data_storage_id','=','entity_states.state_id')
->get();
For your reference Laravel Query Builder

Retriving two models and order them by date

I'm trying to retrive the 20 most recent elements from two differents models Post and Link and rank them by the field created_at in descending order.
Here is the link class
class Link extends \Illuminate\Database\Eloquent\Model {
public $incrementing = false;
public function author() {
return $this->belongsTo('App\Models\Author');
}
public function category() {
return $this->belongsTo('App\Models\Category');
}
}
And here the post class
class Post extends \Illuminate\Database\Eloquent\Model {
public $incrementing = false;
public function author() {
return $this->belongsTo('App\Models\Author');
}
public function category() {
return $this->belongsTo('App\Models\Category');
}
}
How can I do that with eloquent (I'm using it outside Laravel, with Slim)?
use the below code to get recent records
orderBy('created_at', 'DESC')->get();
The merge method was the answer :
$posts = \App\Models\Post::where('draft', false)->orderBy('created_at', 'desc')->take(20)->get();
$links = \App\Models\Link::orderBy('created_at', 'desc')->take(20)->get();
$result = $posts->merge($links)->sortByDesc('created_at')->take(20);

Eloquent relationships in Laravel 4

I'm trying to make a mini CMS-type component and I have three models:
Page.php
class Page extends Eloquent {
protected $table = 'pages';
public function content() {
return $this->hasManyThrough('Content', 'PageGroup');
}
public function groups() {
return $this->hasMany('PageGroup');
}
}
PageGroup.php
class PageGroup extends Eloquent {
protected $table = 'page_groups'
public function group() {
return $this->hasMany("Content");
}
}
Content.php
class Content extends Eloquent {
protected $table = 'content';
public function content() {
return $this->hasMany("Content");
}
}
Edit:
I've set up my relationship models with the correct relationships.
$page = Page::find(1);
$page_group = $page->groups()->where('id', '=', 1)->get();
Returns the PageGroup collection belonging to the Page. I guess my new question is if it's possible to get a collection from that collection... Something like:
$content = $page_group->content;
Because that returns:
Undefined property: Illuminate\Database\Eloquent\Collection::$content
Does this make any sense? I apologize for the newbie question; I'm just getting into Laravel!
I feel like an idiot.
The method chain $page->groups()->where("id", "=", 1)->get()->content; will not work because $page->groups()->where("id", "=", 1); returns a list of rows!
$page->groups()->where("id", "=", 1)->first()->content will work.

Categories