Laravel eloquent: Multiply two columns of two different tables - laravel

My Order Model
class Order extends Model
{
protected $fillable = [
'id','user_id', 'erp_id', 'currency_code','ex_rate_with_base','order_status','status','created_at'
];
protected $hidden = ['updated_at',];
public function orderList(){
return $this->hasMany(OrderList::class);
}
public function currency(){
return $this->belongsTo(Currency::class,'currency_code');
}
}
My Currency Model
class Currency extends Model
{
protected $fillable = [
'currency_code','currency_name', 'currency_symbol', 'ex_rate_with_base', 'update_via', 'status',
];
protected $hidden = [
'created_at','updated_at','updated_by','created_by',
];
protected $primaryKey = 'currency_code';
public $incrementing = false;
public function order()
{
return $this->hasMany(Order::class,'currency_code');
}
}
My OrderList Model
class OrderList extends Model
{
protected $fillable = [
'id','order_id', 'product_code', 'qty','unit_price','status',
];
protected $hidden = [
'created_at' ,'updated_at',
];
public function order(){
return $this->belongsTo(Order::class);
}
}
In my Order controller I want to run the query:
$order_history_list = Order::where([['user_id', $user->id], ['updated_at','>', $updated_at]])
->with([
'currency' => function ($query) {
$query->select('currency_code','currency_symbol','ex_rate_with_base');
},
'orderList' => function ($query) {
$query->select('id','order_id', 'product_code', '***order_lists.qty * orders.ex_rate_with_base AS unit_price_with_ex_rate***','status');
}
])->get();
But error is occuring due to the highlighted portion.
Error: Unknown column 'order_lists.qty * orders.ex_rate_with_base' in 'field list'
Please help me with the correct syntax
How can I use column of order table in the sub query ?

Use DB::raw in your select statement and add a join to the 'orderList' $query
$order_history_list = Order::where([['user_id', $user->id], ['updated_at','>', $updated_at]])
->with([
'currency' => function ($query) {
$query->select('currency_code','currency_symbol','ex_rate_with_base');
},
'orderList' => function ($query) {
$query->select('id','order_id', 'product_code', DB::raw('order_lists.qty * orders.ex_rate_with_base AS unit_price_with_ex_rate'),'status')
->join('orders','order_lists.order_id', 'orders.id');
}
])->get();

My Final Query That Worked:
$order_history_list = Order::where([['user_id',$user->id],['updated_at','>',$updated_at]])
->with(['currency'=>function($query){
$query->select('currency_code','currency_symbol','ex_rate_with_base');
},'orderList' => function($query){
$query->select('order_lists.id','order_lists.order_id', 'order_lists.product_code', 'order_lists.qty','order_lists.unit_price',DB::raw('he_order_lists.qty* he_orders.ex_rate_with_base AS unit_price_with_ex_rate'),'order_lists.status')->join('orders','order_lists.order_id', 'orders.id');
}])->get();

Related

eloquent sum of relation's column in single query

in this query i have three table such as radio, radio_channels and radio_channels_files which into that i want to calculate one column which that is into radio_channels_files table as new column such as duration_sum, my below code work but i can't calculate this column
class Radio extends Model
{
use SoftDeletes;
protected $guarded = ['id'];
protected $casts = [
'logo_path' => 'array',
'cover_path' => 'array'
];
public function category()
{
return $this->belongsTo(RadioCategory::class);
}
public function channels()
{
return $this->hasMany(RadioChannels::class);
}
}
class RadioChannelsFiles extends Model
{
protected $guarded = ['id'];
protected $casts = [
'image' => 'array',
//'keywords' => 'array',
];
public function channel()
{
return $this->belongsTo(RadioChannels::class,'playlist_id');
}
}
class RadioChannels extends Model
{
protected $guarded = ['id'];
protected $casts = [
'image' => 'array'
];
public function channel()
{
return $this->belongsTo(Radio::class);
}
public function files()
{
return $this->hasMany(RadioChannelsFiles::class , 'playlist_id');
}
public function duration_sum()
{
return $this->hasOne(RadioChannelsFiles::class ,'playlist_id')
->select('duration',
DB::raw('sum(duration)')
)->groupBy('duration');
}
}
$channels = Radio::with(['category', 'channels' => function ($query) {
$query->with(['files','duration_sum']);
}])->paginate(50);
i get null output:
#relations: array:2 [▼
"files" => Illuminate\Database\Eloquent\Collection {#1422 ▶}
"duration_sum" => null //should return sum of duration from files
]
i figured out how can i get it
public function getRadiosList(Request $request)
{
$radios = Radio::with(['category', 'playLists' => function ($query) {
$query->with(['files','duration_sum']);
}])->get();
return response()->json(['data' => $radios, 'statusCode' => 1], 200);
}
model:
public function duration_sum()
{
return $this->hasOne(RadioPlaylistsFiles::class, 'playlist_id')
->select('playlist_id',
DB::raw('sum(duration) as `all_duration`')
)->groupBy('playlist_id');
}

laravel adding custom another query into releatinship

in laravel i have this query which that work fine,
$months = Month::with(['lessons' => function ($query) {
$query->with(['files']);
}])->get();
in this query i have $query->with(['files']) which that is:
public function files()
{
return $this->hasMany(LessonFiles::class);
}
i want to add this query for all of $query->with(['files']) rows which that have lesson_file_key:
LessonsView::whereLessonFileKey($lessonFile->lesson_file_key)->count()
it means i want to get count of each row of $query->with(['files']) in this query by adding above code, for example:
$months = Month::with(['lessons' => function ($query) {
$req = $query->with(['files']);
// for example using foreach on $req
// LessonsView::whereLessonFileKey($req->lesson_file_key)->count()
}])->get();
my models:
class Month extends Model
{
protected $guarded = ['id'];
protected $hidden = ['id'];
public function lessons()
{
return $this->hasMany(Lesson::class);
}
public function files()
{
return $this->hasMany(MonthFiles::class);
}
}
class Lesson extends Model
{
protected $guarded = ['id'];
protected $hidden = ['id', 'month_id', 'filename', 'file_url'];
public function month()
{
return $this->belongsTo(Month::class);
}
public function files()
{
return $this->hasMany(LessonFiles::class);
}
}
class LessonFiles extends Model
{
protected $guarded = ['id'];
protected $hidden = ['id', 'lesson_id', 'filename', 'file_url'];
public function lesson()
{
return $this->belongsTo(Lesson::class);
}
public function visits(){
return $this->hasMany(LessonsView::class);
}
}
class LessonsView extends Model
{
protected $guarded = ['id'];
protected $hidden = ['id','user_id','lesson_files_id','lesson_file_key','ip_address'];
public function visitedLesson(){
return $this->belongsTo(LessonFiles::class);
}
}
For something like this you could add a views relationship to you LessonFiles model, something like:
public function views()
{
return $this->hasMany(LessonsView::class, 'lesson_file_key', 'lesson_file_key');
}
Then in your query you can use withCount():
$months = Month::with([
'lessons.files' => function ($query) {
$query->withCount('views');
},
])->get();
Use withCount and whereColumn like this:
$months = Month::with(['lessons' => function ($query) {
$query->with(['files' => function($q) {
$q->withCount(['visits' => function($vq) {
$vq->whereColumn('lesson_views.lesson_file_key', 'lesson_files.lesson_file_key')
}]);
}]);
}])->get();

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 eloquent doesn't use protected table name

In my model i added protected $table, but when i'm going to use it laravel does't use it. This is my role models:
class Role extends Model
{
protected $table = 'role';
protected $primaryKey = 'ROLE_ID';
protected $casts = [
'ACTIVE' => 'boolean',
];
protected $fillable = [
'ROLE', 'ACTIVE', 'TYPE'
];
public $timestamps = false;
public function groups()
{
return $this->belongsToMany(Group::class, GroupRole::class, 'ROLE_ID', 'GROUP_ID');
}
}
And this is Group model:
class Group extends Model
{
protected $table = 'groups';
protected $primaryKey = 'GROUP_ID';
protected $fillable = [
'GROUP_ID', 'GROUP_NAME', 'PARENT_GROUP', 'ACTIVE'
];
protected $casts = [
'ACTIVE' => 'boolean',
];
public $timestamps = false;
public function type()
{
return $this->belongsTo(GroupType::class, 'TYPE', 'TYPE_ID');
}
public function roles()
{
return $this->belongsToMany(Role::class, GroupRole::class, 'GROUP_ID', 'ROLE_ID');
}
}
And this is group_role table model. It handles many to many relation between role and group:
class GroupRole extends Model
{
protected $table = 'group_role';
protected $primaryKey = 'GROUP_ROLE_ID';
protected $fillable = [
'COMMENT', 'ROLE_ID', 'GROUP_ID'
];
public $timestamps = false;
}
Problem begin when i want to use this models. For example:
$role = App\Role::first();
$groups = $role->groups;
Laravel returns this error messages:
SQLSTATE[42S02]: Base table or view not found: 1146 Table 'favian_mydb.App\GroupRole' doesn't exist (SQL: select groups.*, App\GroupRole.ROLE_ID as pivot_ROLE_ID, App\GroupRole.GROUP_ID as pivot_GROUP_ID from groups inner join App\GroupRole on groups.GROUP_ID = App\GroupRole.GROUP_ID where App\GroupRole.ROLE_ID = 1)
I tried to replace App\GroupRole with group_role and executing in mysql. It works fine. Am i missing something?
The Problem is in your roles relation:
public function roles()
{
return $this->belongsToMany(Role::class, GroupRole::class,'GROUP_ID','ROLE_ID');
}
The belongsToMany expects the intermediate table name as second argument, not the class name.
So you have to define it like this:
public function roles()
{
return $this->belongsToMany(Role::class, 'group_role','GROUP_ID','ROLE_ID');
}
I think the problem is in you relation functions. Try to use strings instead of Model::class.
Example:
return $this->return $this->belongsTo('App\GroupType', 'TYPE', 'TYPE_ID');
Hope this works.

Resources