Laravel - Model Eloquent without relationships - php

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

Related

Laravel eloquent scope always returns a collection

I have the following model:
class EmailAddress extends Model
{
public function scopePrimary($query)
{
return $query->firstWhere('is_primary', true);
}
}
class User extends Model
{
public function emailAddresses()
{
return $this->hasMany(EmailAddress::class);
}
}
echo $user->emailAddresses()->primary()->get();
I would expect Laravel to return a model since firstWhere() essentially does LIMIT 1 in the query but instead I always get a collection with one model. Am I doing something wrong? How to fix that?
Thanks in advance!
Maybe you can utilize the hasOne of many relationship:
class User extends Model
{
public function primaryEmailAddress()
{
$this->hasOne(EmailAddresses::class)->ofMany([], function ($query) {
$query->where('is_primary', true);
});
}
}

How to get a single element with a model with relations Laravel

I have three models Driver Worker and Group. The models are like this:
class Group extends Model
{
.....
public function driver()
{
return $this->belongsTo('App\Driver');
}
public function worker()
{
return $this->belongsTo('App\Worker');
}
}
Drivers
class Driver extends Model
{
public function groups()
{
return $this->hasMany('App\Group');
}
}
Worker
class Workerextends Model
{
public function groups()
{
return $this->hasMany('App\Group');
}
}
But how can I get a single element with the relationships that I have defined in my models. I have this in my controller but I only get the first element of the table. I need to get the element with the id and also the relations.
public function show(Group $group)
{
return $group->with(['worker','driver'])->first();
}
try this
public function show(Group $group,$id){
$group = $group->where('id',$id)->with(['worker','driver'])->first();
return $group
}
in your Route
Route::get('/group/show/{id}', 'GroupController#show')->name('group.show');

Laravel Dingo get data from multiple tables

I'm trying to retrieve data from two tables with relationship one-to-many. I need it to return in one response since it will be displayed simultaneously. However, I don't understand how to return extended object. For now I have something like this in controller
public function show(Site $id)
{
foreach ($id->features() as $feature) {
$id->features[] = $feature;
}
return $id;
}
And this is my model
class Site extends Model
{
protected $fillable = ['path', 'site_link'];
public $timestamps = false;
public function features() {
return $this->hasMany('App\SiteFeature');
}
}
For now it returns an empty array of features property.
If you are using implicit model binding then Lazy eager Load features relationship in controller action because model is already loaded
public function show(Site $site)
{
$site->load('features');
return $site;
}
If no implicit model binding then Eager load features using with at time of model loading
public function show($id)
{
$site = Site::with('features')->find($id);
return $site;
}
Check details for loading relationship https://laravel.com/docs/5.6/eloquent-relationships#constraining-eager-loads

Load Eloquent Model Relationships Child Nodes in Laravel 5.1

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

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

Categories