Hi I am implement polymorph relation in laravel framework
currently i have 2 models
CreditLog and User
Creditlog has property sourceable , which is sourceable to User model
class CreditLog extends Model
{
...
public function sourceable()
{
return $this->morphTo();
}
...
}
And then in User i have relation like this
class User extends Authenticatable
{
public function creditLogs()
{
return $this->morphMany('App\Models\CreditLog', 'sourceable');
}
}
And then in some controller i need to get user credit log
$user = User::find($id);
$CreditLogs = $user->creditLogs;
Can i adding parameter in creditLogs method , i mean can laravel morphMany add the parameter like this
$CreditLogs = $user->creditLogs
->where('created_at', '>=', $inputReq['start'])
->where('created_at', '<=', $inputReq['end']);
Thank you for responses the question
You can use load() method with lazy eager loading.
$user->load(['creditLogs' => function ($query) use($inputReq) {
$query->where('created_at', '>=', $inputReq['start'])
->where('created_at', '<=', $$inputReq['end']);
}]);
Or use with() methid with Constraing eager loading
Related
I'm working on a Laravel project, where i have the models "Reservation" and "Week".
The model "Week" has a starting date and a price, the model "Reservation" has a starting date and an ending date.
I want to be able to do a eloquent selection like this: Reservation::with('weeks')->get(), but if i do something below eloquent doesn't recognize it as a relationship, and i can't use "HasMany" in Reservation model because i don't associate the tables with ids, but only with dates.
How can i get the weeks as a relationship?
class Reservation extends Model
{
public function weeks()
{
return Week::whereDate('starting_date', '>=', $this->starting_date)
->whereDate('starting_date', '<', $this->ending_date)
->orderBy('starting_date')
->get();
}
}
edited: thanks #Tim Lewis
I finally managed it thanks this repository: https://github.com/johnnyfreeman/laravel-custom-relation
The repository is archived and not installable for Laravel 8, so i just copied the files in this folders:
app\Relations\Custom.php
app\Traits\HasCustomRelations.php
This allows me to use Reservation::with('weeks')->get(); with eadger constraints
use App\Models\Week;
use App\Traits\HasCustomRelations;
class Reservation extends Model
{
use HasCustomRelations;
public function weeks()
{
return $this->custom(
Week::class,
// add constraints
function ($relation) {
if($this->starting_date && $this->ending_date) {
$relation->getQuery()
->where('weeks.starting_date', '>=', $this->starting_date)
->where('weeks.starting_date', '<', $this->ending_date);
}
else {
$relation->getQuery();
}
},
// add eager constraints
function ($relation, $models) {
$starting_date = $models[0]->starting_date;
$ending_date = $models[count($models)-1]->ending_date;
$relation->getQuery()
->where('weeks.starting_date', '>=', $starting_date)
->where('weeks.starting_date', '<', $ending_date);
},
// add eager matcher
function ($models, $results, $foreignTable, $relation) {
foreach ($models as $model) {
$model->setRelation($foreignTable, $results
->where('starting_date', '>=', $model->starting_date)
->where('starting_date', '<', $model->ending_date));
}
return $models;
}
);
}
}
You're almost there. Just use an accessor to get the weeks:
public function getWeeksAttribute()
{
return Week::whereDate('starting_date', '>=', $this->starting_date)
->whereDate('starting_date', '<', $this->ending_date)
->orderBy('starting_date')
->get();
}
and you'll be able to get the weeks as if it were any other attribute. If you need to serialize your model to Json, remember to add weeks to the $appends array in your model.
I have implemented eloquent relationship in my code but Laravel unable to read the function that I created to map the eloquent relationship in the model.
User Model
public function products(){
return $this->hasMany(Product::class,'userid');
}
Product Model
public function users(){
return $this->belongsTo(User::class);
}
Product Controller
$products = Product::with('Users')->Users()->where('users.isActive',1)->get();
return view('product',compact('products'));
I keep getting error from the product controller, I also attached the error that I current encountered as below.
How can I get all the product and user data with the where condition such as "Users.isActive = 1".
Thanks.
You can use whereHas to filter from a relationship.
$products = Product::with('users')
->whereHas('users', function ($query) {
$query->where('isActive', 1);
})
->get();
Also it is generally a good idea to use singular noun for belongsTo relationship because it returns an object, not a collection.
public function user() {
return $this->belongsTo(User::class);
}
$products = Product::with('user')
->whereHas('user', function ($query) {
$query->where('isActive', 1);
})
->get();
EDIT
If you want to retrieve users with products you should query with User model.
$users = User::with('products')
->where('isActive', 1)
->get();
Then you can retrieve both users and products by
foreach($users as $user) {
$user->products;
// or
foreach($users->products as $product) {
$product;
}
}
You can use whereHas() method for this purpose. Here is the doc
$products = Product::with('users')->whereHas('users', function (Illuminate\Database\Eloquent\Builder $query) {
$query->where('isActive', 1);
})->get();
$users = $products->pluck('users');
return view('product',compact('products'));
You have a typo after the with, is users instead of Users and you're redundant about the Query Builder, remove the ->Users():
Before:
$products = Product::with('Users')->Users()->where('users.isActive',1)->get();
return view('product',compact('products'));
After:
$products = Product::with('users')->where('users.isActive',1)->get();
return view('product',compact('products'));
Fix that and all should work.
I'm developing a web API with Laravel 5.0 but I'm not sure about a specific query I'm trying to build.
My classes are as follows:
class Event extends Model {
protected $table = 'events';
public $timestamps = false;
public function participants()
{
return $this->hasMany('App\Participant', 'IDEvent', 'ID');
}
public function owner()
{
return $this->hasOne('App\User', 'ID', 'IDOwner');
}
}
and
class Participant extends Model {
protected $table = 'participants';
public $timestamps = false;
public function user()
{
return $this->belongTo('App\User', 'IDUser', 'ID');
}
public function event()
{
return $this->belongTo('App\Event', 'IDEvent', 'ID');
}
}
Now, I want to get all the events with a specific participant.
I tried with:
Event::with('participants')->where('IDUser', 1)->get();
but the where condition is applied on the Event and not on its Participants. The following gives me an exception:
Participant::where('IDUser', 1)->event()->get();
I know that I can write this:
$list = Participant::where('IDUser', 1)->get();
for($item in $list) {
$event = $item->event;
// ... other code ...
}
but it doesn't seem very efficient to send so many queries to the server.
What is the best way to perform a where through a model relationship using Laravel 5 and Eloquent?
The correct syntax to do this on your relations is:
Event::whereHas('participants', function ($query) {
return $query->where('IDUser', '=', 1);
})->get();
This will return Events where Participants have a user ID of 1. If the Participant doesn't have a user ID of 1, the Event will NOT be returned.
Read more at https://laravel.com/docs/5.8/eloquent-relationships#eager-loading
#Cermbo's answer is not related to this question. In that answer, Laravel will give you all Events if each Event has 'participants' with IdUser of 1.
But if you want to get all Events with all 'participants' provided that all 'participants' have a IdUser of 1, then you should do something like this :
Event::with(["participants" => function($q){
$q->where('participants.IdUser', '=', 1);
}])
N.B:
In where use your table name, not Model name.
for laravel 8.57+
Event::whereRelation('participants', 'IDUser', '=', 1)->get();
With multiple joins, use something like this code:
$userId = 44;
Event::with(["owner", "participants" => function($q) use($userId ){
$q->where('participants.IdUser', '=', 1);
//$q->where('some other field', $userId );
}])
Use this code:
return Deal::with(["redeem" => function($q){
$q->where('user_id', '=', 1);
}])->get();
for laravel 8 use this instead
Event::whereHas('participants', function ($query) {
$query->where('user_id', '=', 1);
})->get();
this will return events that only with partcipats with user id 1 with that event relastionship,
I created a custom query scope in BaseModel (my all models extends this class):
/**
* Add a relationship exists condition (BelongsTo).
*
* #param Builder $query
* #param string|Model $relation Relation string name or you can try pass directly model and method will try guess relationship
* #param mixed $modelOrKey
* #return Builder|static
*/
public function scopeWhereHasRelated(Builder $query, $relation, $modelOrKey = null)
{
if ($relation instanceof Model && $modelOrKey === null) {
$modelOrKey = $relation;
$relation = Str::camel(class_basename($relation));
}
return $query->whereHas($relation, static function (Builder $query) use ($modelOrKey) {
return $query->whereKey($modelOrKey instanceof Model ? $modelOrKey->getKey() : $modelOrKey);
});
}
You can use it in many contexts for example:
Event::whereHasRelated('participants', 1)->isNotEmpty(); // where has participant with id = 1
Furthermore, you can try to omit relationship name and pass just model:
$participant = Participant::find(1);
Event::whereHasRelated($participant)->first(); // guess relationship based on class name and get id from model instance
[OOT]
A bit OOT, but this question is the most closest topic with my question.
Here is an example if you want to show Event where ALL participant meet certain requirement. Let's say, event where ALL the participant has fully paid. So, it WILL NOT return events which having one or more participants that haven't fully paid .
Simply use the whereDoesntHave of the others 2 statuses.
Let's say the statuses are haven't paid at all [eq:1], paid some of it [eq:2], and fully paid [eq:3]
Event::whereDoesntHave('participants', function ($query) {
return $query->whereRaw('payment = 1 or payment = 2');
})->get();
Tested on Laravel 5.8 - 7.x
i need help for Laravel 4.2
the models are:
//1. model kelengkapan
class Kelengkapan extends Eloquent{
public function detilKelengkapan(){
return $this->hasMany('DetilKelengkapan', 'id_kelengkapan');
}
}
// 2. model DetilKelengkapan
class DetilKelengkapan extends Eloquent{
public function tDetilKelengkapanPaket(){
return $this->hasMany('TDetilKelengkapanPaket', 'id_detil_kelengkapan');
}
public function kelengkapan(){
return $this->belongsTo('Kelengkapan', 'id_kelengkapan');
}
}
// 3. model TDetilKelengkapanPaket
class TDetilKelengkapanPaket extends Eloquent{
public function detilKelengkapan(){
return $this->belongsTo('DetilKelengkapan', 'id_detil_kelengkapan');
}
}
the controller is:
$kelengkapan = Kelengkapan::with('detilKelengkapan.tDetilKelengkapanPaket')
->whereHas('detilKelengkapan.tDetilKelengkapanPaket', function($q) use ($id){
$q->where('id_paket', $paket);
})->get();
but the result has not filtering by "id_paket" but showed all data. thanks. (newbie)
Your Code:
$kelengkapan = Kelengkapan::with('detilKelengkapan.tDetilKelengkapanPaket')
->whereHas('detilKelengkapan.tDetilKelengkapanPaket', function($q) use ($id){
$q->where('id_paket', $paket);
})->get();
The correct Code:
$kelengkapan = Kelengkapan::with('detilKelengkapan.tDetilKelengkapanPaket')
->whereHas('detilKelengkapan.tDetilKelengkapanPaket', function($q) use ($id){
//the function should return the $q variable.
return $q->where('id_paket', $id);
})->get();
Explanation:
whereHas function has 2 compulsory arguments. A relationship function name, and a closure. The closure must return a query object so that filters can be chained.
Source: http://laravel.com/docs/4.2/eloquent#querying-relations
In there whereHas function you pass $id variable in the closure but you are using $packet inside.
$kelengkapan = Kelengkapan::with('detilKelengkapan.tDetilKelengkapanPaket')
->whereHas('detilKelengkapan.tDetilKelengkapanPaket', function($q) use ($id){
$q->where('id_paket', $id);
//---------------------^
})->get();
Try it and let me know the result.
How to search by title in the ServiceType only? There is also a title field in the Package which should be avoided
For example, in the Model:
class Package extends Eloquent {
protected $table = 'package';
function serviceType()
{
return $this->belongsTo('ServiceType');
}
public static function getPackagesByServiceType($service)
{
return Package::with('serviceType')->where('title', '=', $service);
}
}
Note:
There is a service_type_id field in the Package and id, title fields in the serviceType
in the controller:
$packages = Package::getPackagesByServiceType('something')->get();
No result appeared for some reason? It should search for something in the serviceType
It seem it wouldn't work to combine with() and where(). When I remove the where() and it work.
You can't use where() like that to filter by a related model. You should use whereHas() instead:
public static function getPackagesByServiceType($service)
{
return Package::with('serviceType')->whereHas('serviceType', function($q) use ($service){
$q->where('title', '=', $service);
});
}
Note if you don't need serviceType in the packages afterwards you don't have to eager load it, ergo you can remove the with('serviceType')
Also if you call get() in the controller you should use a query scope. It offers the same functionality but it's not a static function and it's the Laravel way
public function scopeByServiceType($query, $service){
return $query->with('serviceType')->whereHas('serviceType', function($q) use ($service){
$q->where('title', '=', $service);
});
}
And you use it like this:
$packages = Package::byServiceType('something')->get();
class Package extends Eloquent {
protected $table = 'package';
function serviceType()
{
return $this->belongsTo('ServiceType');
}
public static function getPackagesByServiceType($service)
{
return Package::with('serviceType')->where('title', '=', $service)->get();
}
}
You forgot the ->get();
The ->get() should be in the Model
public static function getPackagesByServiceType($service)
{
return Package::with('serviceType')->where('title', '=', $service)->get(); // here
}
and in the controller it should be like this:
$packages = Package::getPackagesByServiceType('something');
Hope that helps... I had similar issues in my Model - Controller structure....