Is there a way to transform this query builder to eloquent?
$transactions = DB::table('transactions')
->join('accounts', 'transactions.account_id', '=', 'accounts.id')
->select('transactions.*', 'accounts.name as account_name')
->paginate(5);
I tried it with One To Many. But it need the find() function so it give me one account's transactions but I need to select all transactions with accounts.name
In comments, you've said you have one to many relationship defined (I assume it's Accounts has many Transactions) and you need to get all transactions with account name, so do this:
Transaction::with('account')->paginate(5);
Where account is relationship:
public function account()
{
return $this->belongsTo(Account::class);
}
Then you'll be able to display the data like this:
#foreach ($transactions as $transaction)
{{ $transaction->id }}
{{ $transaction->account->name }}
#endforeach
You will need to use models to do that.
Transaction model and Account model.
Define their relationships
Create a method in the transaction model to retrieve the related account names.
function accoutNames() { //blablabla }
Do the query in controller, something like that:
Transaction->accountNames();
Related
I have Users table,Jobs table and JobStatus table. I get user jobs using relationship
return User::find($dto->getUserId())
->jobs()
This will return all user jobs as collection, not as relationship inside user model.
Now I need to get jobs statuses, but when I try this
User::find($dto->getUserId())
->jobs()
->statuses()
I get error Call to undefined method. I need to get statuses as collection so I can use where,sort by etc while getting them from db. Is there any way to do so?
I need to do something like this , but with statuses
return User::find($dto->getUserId())
->jobs()
->has('status')
->where('role','responsible')
->where('jobs.created_at','>=',Carbon::now()->subDays($dto->getPeriod())->toDateString())
->get();
To retrieve the jobs by filtering on the statuses relationship, you can do it like this:
$user->jobs()->whereHas('statuses', function ($query) {
// Perform filter on the query for jobs->statuses
})->get();
For more information about querying relationship existence: https://laravel.com/docs/7.x/eloquent-relationships#querying-relationship-existence
If you want to retrieve the statuses instances, you can do it like this:
$statuses = JobStatus::where('created_at', '>=', now())
->whereHas('jobs', function ($query) use ($user) {
$query->whereUserId($user->id);
})
->get();
Just use jobs without parenthesises to get the model itself :
User::find($dto->getUserId())
->jobs
->statuses;
define your statuses() function first with the relations in your model with the jobs
like many to many or one to many relationship
public function statuses(){
return $this->belongsToMany('App\Job')->withTimestamps();
}
I understand this might be really simple but I cannot get my head around it.
Say I am fetching all tickets
$tickets = Ticket::all();
And with a single line, I want to fetch all the users associated with each ticker, (every ticket has a field with user_id), is there a single line of code, which can do it in Laravel. I can do the old way to loop though each ticket and fecth the details for each user as below, but am just looking for best practices here.
foreach($tickets as $ticket):
$ticket->user = User::find($ticket->user_id);
endforeach;
i'm assuming you have defined a correct relationship in your models.
You can use eloquent relationship of laravel to get all tickets of users
$tickets = User::with('tickets')->get();
to get data if user has at least one ticket you can use the below code
$tickets = User::has('tickets')->get();
To get all tickets only:
$tickets = Ticket::all();
and then in your blade you can do:
#foreach($tickets as $ticket)
// getting user using relationship
{{ $ticket->user->name }}
#endforeach
or to get tickets associated with user you can use
$tickets = Ticket::whereHas('user', function ($q) {
$q->with('user');
})
->get();
to know more about relationships visit this
The first, you declare relation model Ticket with model User:
This is code in model Ticket:
public function user()
{
return $this->hasOne('App\Model\User', 'user_id', 'id'); //id is the primary key in User table
}
then fetching all tickets with user info
$tickets = Ticket::load('user')->all();
or
$tickets = Ticket::with('user')->all();
If you want to get the list of all tickets where has user, with the user associated with each ticket, try this:
$tickets = Ticket::whereHas('user', function ($query) {
$query->with('user');
})
->get();
If you are sure that all tickets have an associated user, use this:
$tickets = Ticket::with('user')->get();
I've got 3 tables, the users table, the image table, and the favorites table which works sort of like a pivot table, as all it has is ID, image_id, and user_id.
In my user model, I have:
public function FavoritedByMe() {
return $this->hasMany('CommendMe\Models\Favorite', 'user_id');
}
In my favorites controller, I have:
public function getFavorites($username) {
$user = User::where('username', $username)->first();
return view('user.favorites')
->with('user', $user);
}
and this works just fine if I want to get the IDs of all the images I've favorited:
#foreach ($user->FavoritedByMe as $favorite)
{{ $favorite->image_id }}
#endforeach
However, what I'd really like to be able to return the view with the images themselves. Something like:
$favImages = Images::where('id', $user->FavoritedByMe->image_id);
return view('user.favorites')
->with('user', $user)
->with('favImages', $favImages);
Now obviously this won't work, and will return the error:
ErrorException in FavoritesController.php line 54: Undefined property: Illuminate\Database\Eloquent\Collection::$image_id
but perhaps some kind of Eloquent relationship would? I've tried making those work but they just don't "click" in my head.
How could I make this work?
Thanks in advance!
In your Favorite model add this relationship:
public function image()
{
return $this->belongsTo('YourImageModel');
}
Then you can acces the image like this:
#foreach ($user->FavoritedImages as $favorite)
{{ $favorite->image->yourProperty }}
#endforeach
In the laravel's best practices you should call your FavoritedByMe relationship favorites since it's obviously related to the user.
I have a laravel query as the one below:
$campaign = Campaign::with(array('tracks.flights' => function($q) use ($dates)
{
$q->whereRaw("flights.start_date BETWEEN '". $dates['start']."' AND '".$dates['end']."'")->orderBy('start_date')
->with('asset')
->with('comments');
}
))
->with('tracks.group')
->with('tracks.media')
->orderBy('created_at', 'desc')
->find($id);
I am very new to laravel and right now the response from this query returns all the data required including the comments with the comments attributes from the DB.
What i want to achieve is manipulate the comments object so it includes the user name from the users table as the comments table has the user_id only as an attribute.
How can I achieve this? I am very new to laravel.
Your Comment model must have a relationship with the User model, such as:
public function user()
{
return $this->belongsTo('App\User');
}
Now when you are iterating comments you are able to do $comment->user->name or in your case it will be something like this:
#if(!$campaign->tracks->flights->isEmpty())
#foreach($campaign->tracks->flights as $flight)
#if(!$flight->comments->isEmpty())
#foreach($flight->comments as $comment)
{!! $comment->user->name !!}
#endforeach
#endif
#endforeach
#endif
Once you can do this, next step is to understand eager load with eloquent.
I got this query:
$users = DB::table('users')->whereExists(function($query)
{
$query->select(DB::raw(1))
->from('galleries')
->whereRaw('galleries.user_id = users.id');
})->get();
This query selects all users who have gallery. Problem is that I can't use eloquent releationships now. Whenever i try to loop like this:
#foreach ($user->gallery as $gallery)
{{$gallery->name}}
#endforeach
I get error:
Undefined property: stdClass::$gallery
It happens with all other tables. What am I doing wrong here? My realationships are defined and they work just fine, i got problems only in this query. Thanks.
EDIT
Since it's not eloquent query, could you show me example how to write query, into few tables with eloquent. For example, I need all users who have their status approved in example table
First, determine a relationship in the User class, like this:
class User {
// Determine relation to Example table
public function examples() {
return $this->hasMany('Example', 'user_id', 'id'); // second parameter is the foreign key
}
}
Then the query:
User::whereHas('examples', function( $query ) {
$query->where('status','approved');
})->get();