I have following query which works fine and gives result for StatusType
AddOnModel::with('StatusType')->get();
But when I write below, it does not bind StatusType Records
AddOnModel
::select(\DB::Raw('A.AddOnID, A.AddOn, Count(R.AddOnID) as Total'))
->from( 'tblAddOn as A' )
->with('StatusType')
->leftjoin( 'tblrevenue as R', \DB::raw( 'R.AddOnID' ), '=', \DB::raw( 'A.AddOnID' ) )
->groupBy("A.AddOnID", "A.AddOn")->get();
The part which does not work is this one: ->with('StatusType')
Am I doing something incorrectly?
Here is the Model
class AddOnModel extends Model {
public $table = 'tbladdon';
public $primaryKey = 'AddOnID';
public $timestamps = true;
public function StatusType() {
return $this->hasOne('\StatusTypeModel', 'StatusTypeID', 'StatusTypeID');
}
}
you can do this as a solution, make toArray() method in AddOn model, make that method returns what you need id, name, etc, like this:
return [
'id' => $this->id,
'StatusType' => this->StatusType
]
You use with() after ->leftjoin may be this will affect. Try below code:
AddOnModel::with('StatusType')
->select(\DB::Raw('A.AddOnID, A.AddOn, Count(R.AddOnID) as Total'))
->from( 'tblAddOn as A' )
->leftjoin( 'tblrevenue as R', \DB::raw( 'R.AddOnID' ), '=', \DB::raw( 'A.AddOnID' ) )
->groupBy("A.AddOnID", "A.AddOn")
->get();
Hpoe this will work for you.
Related
I'm studying table relation in Laravel6. Here is my code which works but suddenly all records Created_at time displayed the same 2021-08-02 11:34:30. I'm sure that time was right. but I noticed it all same. Could you teach me how to fix please?
I would like to get the products table's created_at.
class ProductController extends Controller {
public function index() {
$products = Product::All();
$products = Product::with('categori')
->join('creators', 'creators.id', '=', 'products.creator_id')
->join('categoris', 'categoris.id', '=', 'products.categori_id')
->join('branches', 'branches.id', '=', 'products.br_id')
->join('users', 'users.id', '=', 'products.user_id')
->join('colors', 'colors.id', '=', 'products.color_id')
->get();
$data = array(
'title' => 'index',
'no' => 1,
'products' => $products,
'created_at' => created_at,
);
return view('product.index',$data);
}
Here is my blade file
{{ $product->created_at->format('Y-m-d H:i:s') }}
UPDATE: Model Produt
use Illuminate\Database\Eloquent\Model;
class Product extends Model {
protected $fillable = ['title','kansu', 'customer', 'memo', 'status', 'memo2', 'color_id', 'creator_id', 'br_id','user_id' ,'categori_id'];
public function categori()
{
return $this->belongsTo(Categori::class);
}
}
Produts Table image
I'm not familiar with format() method. You could try to use PHP date_format() to see if there is any difference.
#Bladeview:
{{ date_format($product->created_at, 'Y-m-d H:i:s') }}
Related docs: https://www.php.net/manual/en/datetime.format.php
I have 3 tables this table is related to, I will call this table with
belanja (parent)
anak_belanja (child)
supplier (has relation with parent)
I can create this relation from parent and child but on table supplier I get an error. Usually I use "with" and I get no error, but now I use query builder and I have a problem
My Belanja Model
public function supplier()
{
return $this->belongsTo(\App\Models\Suplier::class ,'supplier_id');
}
My Anak_Belanja model
public function belanja()
{
return $this->belongsTo(\App\Models\Belanja::class ,'belanja_id');
}
and this is my controller
public function render()
{
$user_id = Auth::user()->id;
$sub = SubRincianUraianKegiatan::where('user_id', $user_id)
->where('id' , $this->newid)
->pluck('uraian', 'id');
$sup = Supplier::all()->pluck('nama' ,'id');
$data = DB::table('belanja AS t')
->select([
't.id',
't.uraian',
't.tgl_belanja',
't.supplier_id',
DB::raw('coalesce(sum(p.harga * p.qty),0) AS total_order')
])
->leftjoin('suplier AS s','t.suplier_id','=','s.id') // on here i think this error
->leftjoin('anak_belanja AS p','p.belanja_id','=','t.id')
->where('sub_id', $this->newid)
->where('uraian', 'like', '%'.$this->search.'%')
->groupBy('t.id')
->groupBy('t.uraian')
->groupBy('t.tgl_belanja')
->groupBy('t.suplier_id')
->paginate(10);
return view('livewire.detail-belanja-lw',
['data' => $data ,
'sup' => $sup,
'sub' => $sub,
]);
}
In my blade I try to add supplier like that
{{$i->supplier->nama}}
but I get an error
Undefined property: stdClass::$supplier
Can someone explain my mistake?
$data = DB::table('belanja AS t')
->select([
't.id',
't.uraian',
't.tgl_belanja',
't.suplier_id',
DB::raw('coalesce(sum(p.harga * p.qty),0) AS total_order'),
DB::raw('s.nama as nama')
])
->leftjoin('suplier AS s','t.suplier_id','=','s.id') // on here i think this error
->leftjoin('anak_belanja AS p','p.belanja_id','=','t.id')
->where('sub_id', $this->newid)
->where('uraian', 'like', '%'.$this->search.'%')
->groupBy('t.id')
->groupBy('t.uraian')
->groupBy('t.tgl_belanja')
->groupBy('t.suplier_id')
->paginate(10);
try this.
In my Laravel-5.8 project, I am developing employee leave application. In the application, in a particular year, each employee can apply for different leaves. when an employee logs in I want to display a table as shown below that shows Leave Balance of each leave type name of the logged in user
I have 3 tables that are applicable
class HrLeaveType extends Model
{
protected $table = hr_'leave_types';
protected $fillable = [
'id',
'leave_type_name',
];
public function leavetypedetail()
{
return $this->hasMany('App\Models\LeaveTypeDetail');
}
}
class HrLeaveTypeDetail extends Model
{
protected $table = 'hr_leave_type_details';
protected $fillable = [
'id',
'leave_type_id',
'employment_type_id',
'no_of_days',
];
public function leavetype()
{
return $this->belongsTo('App\Models\HrLeaveType', 'leave_type_id', 'id');
}
public function employeetype()
{
return $this->belongsTo('App\Models\HrEmployeeType', 'employee_type_id', 'id' );
}
}
class HrLeaveRequest extends Model
{
protected $table = 'hr_leave_requests';
protected $fillable = [
'id',
'employee_id',
'leave_type_id',
'leave_status',
'no_of_days',
];
public function employee()
{
return $this->belongsTo('App\Models\HrEmployee','employee_id');
}
public function leavetype()
{
return $this->belongsTo('App\Models\HrLeaveType','leave_category_id');
}
}
As earlier said, the expected result is to have 4 columns (Leave Category
, Applicable Leave, Approved Leave
, Available
)
Controller
public function leave_balance()
{
$userId = Auth::user()->id;
$userCompany = Auth::user()->company_id;
$leaveBalance = DB::table('hr_leave_types AS lt')
->leftJoin('hr_leave_type_details AS ltd', function($join) use ($userCompany)
{
$join->on('ltd.leave_type_id', '=', 'lt.id')
->where('ltd.company_id', '=', $userCompany);
})
->leftJoin('hr_leave_requests AS lr', function($join) use ($userCompany, $userEmployee)
{
$join->on('lr.leave_type_id', '=', 'lt.id')
->where('lr.company_id', '=', $userCompany)
->where('lr.employee_id', '=', $userEmployee)
->whereYear('lr.commencement_date', '=', date('Y'))
->where('lr.leave_status', 4);
})
->leftJoin('hr_employees AS e', function($join) use ($userCompany, $userEmployee)
{
$join->on('e.id', '=', 'lr.employee_id')
->where('e.company_id', '=', $userCompany)
->where('e.id', '=', $userEmployee)
->where('e.employee_type_id', '=', 'ltd.employee_type_id');
})
->where('lt.company_id', '=', $userCompany)
->select(
'lt.leave_type_name as leaveCategory',
'ltd.no_of_days as applicableLeave',
DB::raw("IFNULL(SUM(lr.no_of_days),0) as approvedLeave")
)
->groupBy('lt.leave_type_name', 'e.id')
->get();
return view('leave-balances')
->with('leaveBalance', $leaveBalance);
}
available = applicableLeave - approvedLeave
I want to achieve this result
When I tried to run the controller, I got this error:
#message: "SQLSTATE[42000]: Syntax error or access violation: 1055 'laravelapp.ltd.no_of_days' isn't in GROUP BY (SQL: select lt.leave_type_name as leaveCategory, `l ▶"
There is no way I can group by 'no_of_days'
I only want to group by leave_type_name and employee_id (e.id)
How do I resolve this?
Thanks
This more of a database concern rather than laravel issue. You can only select the columns specified in the group by clause, and you can use any aggregate functions with it.
So one option is to modify your query with the required column
->groupBy('lt.leave_type_name', 'e.id', 'ltd.no_of_days')
Probably you will have to adjust your IF clause on the select as well, since that column is not in the group by
Full Group By is supported in mysql 5.7 but is disabled by default.
How can you fix the full group by issues
How to give alias in replated table hasMany relationship.
Controller
$templates = UserMaster::where ( 'INACTIVE', '=', 0 )->with('contact')->get ();
Model
public function contact(){
return $this->hasMany(\App\Models\Contact::class,'CONTACT_ID');
}
I can try this code my but give error
$templates = UserMaster::where ( 'INACTIVE', '=', 0 )->with('contact as CONTACT')->get ();
So how give alias in with query?
Thank you
Commodity:
public function variations() {
return $this->hasMany( CommodityVariation::class )->with( 'unit' );
}
Recipe:
public function commodity_variations() {
return $this->belongsToMany( CommodityVariation::class, 'recipe_commodity_variations' )->with( 'commodity' )->withTimestamps();
}
CommodityVariation:
public function commodity() {
return $this->belongsTo( Commodity::class )->with( 'variations', 'allergens' );
}
public function recipes() {
return $this->belongsToMany( Recipe::class, 'recipe_commodity_variations' )->withTimestamps();
}
What I'm looking for:
I would like to get all recipes that use/have this specific commodity, but I've to go through my commodity_variations to find the relation between recipe and commodity. This is because recipe is linked to commodity variations and commodity variations is linked to commodity.
So what I've build so far, is this, but it just returns 50 recipes regardleess of what commodity_id I enter. For instance if I write 100000 instead of $commodity->id this returns 50 recipes aswell.
$recipe = $department->recipes()->with(["commodity_variations" => function($q) use ( $commodity ) {
$q->where('commodity_variations.commodity_id', '=', $commodity->id);
}])->get();
I really can't figure out what I'm doing wrong. I might be misunderstanding some basic stuff on how these relations work.
Edit:
here is another example
$commodity_variations = $recipe->commodity_variations()->with( [
'commodity' => function ( $query ) use ( $commodity ) {
$query->where( 'commodities.id', $commodity->id );
}
] )->get();
Should return only the commodity variations that have commodity->id = 11, but it returns all. Like it's completely ignoring the where part of my query.
Try this once.
$commodity_variations = $recipe->whereHas('commodity_variations' ,
function ( $query ) use ( $commodity ) {
return $query->where( 'commodity_variations.commodity_id', $commodity->id );
}
)->get();
Also refer this: http://laravel.com/docs/4.2/eloquent#querying-relations
Here is a working solution. Made a new model taking care of the many to many relation between recipe and commodityvariation.
class RecipeCommodityVariations extends Model {
/**
* The database table used by the model.
*
* #var string
*/
protected $table = 'recipe_commodity_variations';
}
Query:
$recipeCommodityVariations = RecipeCommodityVariations::whereIn( 'recipe_id', $department->recipes()->pluck( 'recipe_id' ) )->whereIn( 'commodity_variation_id', $commodity->variations()->pluck( 'id' ) )->pluck( 'recipe_id' )
What troubles me, is that I feel like I'm doing it wrong... It's pretty annoying.