Laravel complexe relationships - laravel

I need help please, to figure out for convenient ways to link between User/Staff/Parent/Student.
A Staff/Parent/Student is a user.
A Staff can be a Parent too. Similarly, a Parent may be a Staff too.
A student belongsToMany Parent, and a Parent belongsToMany Student.
Here are the models I've created :
App\Models\Student.php
protected $fillable = [
'name',
'email',
'student_user_id',
'created_at',
'updated_at',
'deleted_at',
];
public function student_user()
{
return $this->belongsTo(User::class, 'student_user_id');
}
public function guardians()
{
return $this->belongsToMany(StudentGuardian::class);
}
==========================================================
App\Models\StudentGuardian.php
protected $fillable = [
'name',
'email',
'guardian_user_id',
'is_staff',
'guardian_staff_id',
'created_at',
'updated_at',
'deleted_at',
];
public function students()
{
return $this->belongsToMany(Student::class);
}
public function guardian_user()
{
return $this->belongsTo(User::class, 'guardian_user_id');
}
public function guardian_staff()
{
return $this->belongsTo(Staff::class, 'guardian_staff_id');
}
=====================================
App\Models\Staff.php
protected $fillable = [
'name',
'email',
'staff_user_id',
'staff_guardian_id',
'is_student_guardian',
'created_at',
'updated_at',
'deleted_at',
];
public function staff_user()
{
return $this->belongsTo(User::class, 'staff_user_id');
}
public function staff_guardian()
{
return $this->belongsTo(StudentGuardian::class, 'staff_guardian_id');
}
In the StudentsController, I don't know how to call the students related to the authenticated user

you can use polymorphic relation to handle it.
https://laravel.com/docs/9.x/eloquent-relationships#polymorphic-relationships

Related

Search in Laravel relation using json column

I have problem with search in json column.
I have 3 relations:
products
feature products
feature_values
My tables:
products: https://ibb.co/1dgjT6m
feature products: https://ibb.co/K9f74Wn
feature_values: https://ibb.co/rc3zG5W
My migrations:
Product:
class Product extends Model implements Presentable
{
....
public function featureProducts()
{
return $this->hasMany(FeatureProduct::class, 'product_id');
//return $this->belongsToMany(Feature::class, 'feature_product', 'id');
}
}
FeatureProduct
class FeatureProduct extends Model
{
protected $table = "feature_product";
protected $with = [
'values'
];
public function values()
{
return $this->belongsTo(FeatureValue::class, 'feature_values_ids', 'id');
}
}
FeatureValues:
class FeatureValue extends Model
{
use SoftDeletes,
Translatable;
protected $fillable = [
'feature_id',
'value'
];
protected $dates = [
'created_at',
'updated_at',
'deleted_at'
];
protected $translatable = [
'value'
];
public function feature(): BelongsTo
{
return $this->belongsTo(Feature::class);
}
public function getAdminUrlAttribute(): AbstractAdminUrlPresenter
{
return new FeatureValueUrlPresenter($this);
}
}
I need to show products with features and assigned features_values
I heve problem with search in json column: feature_product. feature_values_ids
When I have INT in this column, then this is working fine:
public function values()
{
return $this->belongsTo(FeatureValue::class, 'feature_values_ids', 'id');
}
When I have:
["1", "2","3"]
I haven't any results :(
Haw can I repair it?

Laravel Eloquent HasManyThrough relationship

Trying to get locations through a user. Currently I'm getting an error, so either my hasManyThrough is setup incorrectly or my data structure is. It's still a new project so I don't mind restructuring the database to make the default hasManyThrough work properly.
$user = User::with('locations')->find(Auth::user()->id);
echo '<pre>';
die(print_r($user->locations,true));
Models:
User:
class User extends Authenticatable
{
protected $fillable = [
'name', 'email', 'password',
];
public function locations() {
return $this->hasManyThrough(
Location::class,
UserLocations::class,
);
}
}
UserLocations
class UserLocations extends Model
{
protected $fillable = [
'user_id',
'location_id',
];
public function user()
{
return $this->belongsTo(User::class);
}
public function location()
{
return $this->belongsTo(Location::class);
}
}
Locations
class Location extends Model
{
protected $fillable =
[
'city',
'name',
'timezone',
'email',
'state',
'address',
'address1',
'zip_code',
];
public function user_locations()
{
return $this->hasMany(UserLocations::class);
}
}
Data Structure
Users:
-id
-name
-email
-password
UserLocations:
-id
-user_id
-location_id
Locations:
-id
-name
-city
You should not have used hasManyThrough for this since UserLocations already contains the location_id. In your user model, use hasManyRelationship to UserLocation.
public function locations()
{
return $this->hasMany(UserLocation::class, 'user_id');
}
And then to include the location information, just eager load it.
$user = User::with(['locations.location'])->where('id', Auth::user()->id)->first();

Accessing attribute from different model in Laravel

Please take a look at this screenshot
that is the result from this
salesItem product_id = {{ $salesItem->product_id }}
and this
wh2summary ={{$salesItem->wh2sum}}
How can I access the qty_in in the long result from wh2sum? I can see the qty_in but if i do this {{$salesItem->wh2sum->qty_in}}
i get this error
my Salesitems model
protected $table = 'sales_items';
protected $fillable = [
'product_id',
'sales_id',
'product_name',
'product_code',
'price',
'rate',
'quantity',
'total_price',
];
public function wh2sum()
{
return $this->hasMany('App\Warehouse2StockSummaries', 'product_id', 'product_id');
}
my wh2sum model
class Warehouse2StockSummaries extends Model
{
protected $table = 'warehouse2_summary';
protected $fillable = [
'product_id',
'qty_in',
'qty_out'
];
public function product()
{
return $this->hasOne('App\Products', 'id','product_id');
}
}
for my products model
class Products extends Model
{
// use SoftDeletes;
protected $fillable = [
'product_code',
'name',
'categories_id',
'wh1_limit_warning',
'wh2_limit_warning',
'price',
'selling_price',
'user_id'
];
public function warehouse2StockSummary()
{
return $this->hasMany('App\Warehouse2StockSummaries', 'id', 'product_id');
}
public function salesItem()
{
return $this->hasMany('App\Purchaseitems');
}
please help and thank you in advance!

How to count and sum inner relational model in laravel

I am building a small application in Laravel where I got stuck with the sum of inner relational data,
I have a model Company which has Many relation associatedProjects and associatedProjects belongs to relation project and project hasOne technicalDescription.
Company Model:
class Company extends Model {
public function roles()
{
return $this->belongsToMany('Noetic\Plugins\Conxn\Models\Variables\Company\Role', 'company_role_relation', 'company_id', 'role_id')->withTimestamps();
}
public function specialisations()
{
return $this->belongsToMany('Noetic\Plugins\Conxn\Models\Variables\Company\Role', 'company_specialisation_relation', 'company_id', 'specialisation_id')->withTimestamps();
}
public function associatedProjects()
{
return $this->hasMany('Noetic\Plugins\Conxn\Models\Project\AssociateCompany','company_id','id');
}
}
AssociateCompany Model:
class AssociateCompany extends Model {
protected $table = 'project_associate_company';
protected $fillable = [
'project_id', 'company_role_id', 'company_specialisation_id', 'company_id', 'link', 'file_name'
];
public function project()
{
return $this->belongsTo('Noetic\Plugins\Conxn\Models\Project','project_id','id');
}
public function company()
{
return $this->belongsTo('Noetic\Plugins\Conxn\Models\Company','company_id','id');
}
public function companyRole()
{
return $this->belongsTo('Noetic\Plugins\Conxn\Models\Variables\Company\Role',
'company_role_id','id');
}
public function specialisation()
{
return $this->belongsTo('Noetic\Plugins\Conxn\Models\Variables\Company\Role',
'company_specialisation_id','id');
}
}
Project Model
class Project extends Model {
protected $fillable = [
'user_id','koshy_id', 'name', 'slug', 'owner_spv', 'spv_link', 'latitude', 'longitude',
'landmark', 'city', 'district', 'state', 'pin_code', 'region_id', 'country', 'building_use',
'sector', 'conxn_id', 'parent_project_id', 'website', 'project_logo', 'tracked', 'verified',
'code_link', 'status', 'active', 'premium','area'
];
public function technicalDescription()
{
return $this->hasOne('Noetic\Plugins\Conxn\Models\Project\TechnicalDescription','project_id','id');
}
public function associateCompany()
{
return $this->hasMany('Noetic\Plugins\Conxn\Models\Project\AssociateCompany','project_id','id');
}
}
Now this technicalDescription has fields construction_cost, now I want to first count total number of associatedProject and fetch sum of all the project's construction_cost which is in technicalDescription, some what I have done this code:
$company = Company:: where( 'status', 'saved')
->withCount( 'associatedProjects' )
->with('associatedProjects.project.technicalDescription')
->get()
->transform(function ($value) {
$value['project_value'] = $value['associatedProjects']->flatten(2)
->pluck('project.technicalDescription')->sum('construction_cost');
return $value;
})
->sortByDesc('project_value')
->forpage( $request->page , 10 );
$next = $request->page+1 ;
$previous =$request->page-1 ? abs($request->page-1):1 ;
I am unable to use paginate over here as laravel collection doesn't have such method, moreover the query logic also doesn't appear accurate.
Any suggestions are welcome. Thanks
You can use a BelongsToMany relationship to get the technicalDescriptions directly:
class Company extends Model {
public function technicalDescriptions() {
return $this->belongsToMany(
'Noetic\Plugins\Conxn\Models\Project\TechnicalDescription',
'project_associate_company',
'company_id',
'project_id',
null,
'project_id'
);
}
}
$company = Company::where('status', 'saved')
->withCount(['technicalDescriptions as project_value' => function($query) {
$query->select(DB::raw('sum(construction_cost)'));
}])
->orderByDesc('project_value')
->paginate();

Laravel 4 relationship and events

I'm having an issue with Eloquent relationship. The relationship is... Each User can have an Owner which is also a user.
When I try to fetch User with Parent:
On *nix OS and PHP 5.4.20, I get same User as Parent so parent and user both are same.
Whereas on PHP5.4.7 (Win 7 if that matters), it returns correct data. By the way this code is an Event Handler of some event.
User Model
class User extends Eloquent implements UserInterface, RemindableInterface, PresentableInterface {
protected $fillable = array(
'first_name', 'last_name', 'email', 'password', 're_type_password', 'birth_date',
'phone', 'address', 'state', 'city', 'zip', 'profile_pic', 'owner_id', 'can_edit_appointments',
'can_accept_invitations', 'can_edit_profile', 'can_receive_notification', 'is_active', 'is_admin', 'token', 'failed_login_attempts_count'
);
public function __construct($validator = null, $subAccountValidator = null)
{
parent::__construct();
$this->validator = $validator ?: App::make('ReminderMillie\Services\Validators\UserValidator');
$this->subAccountValidator = $subAccountValidator ?: App::make('ReminderMillie\Services\Validators\SubAccountValidator');
}
public function getDates()
{
return array('created_at', 'updated_at', 'birth_date');
}
/**
* Relations
*/
public function business()
{
return $this->hasOne('Business', 'owner_id');
}
public function parent()
{
return $this->belongsTo('User', 'owner_id');
}
public function subAccounts()
{
return $this->hasMany('User', 'owner_id');
}
}
I think you inverse is incorect...
please check this
public function parent()
{
return $this->belongsTo('User');
}
public function subAccounts()
{
return $this->hasMany('User', 'id', 'owner_id');
}

Resources