Pull data based on related table - laravel

I have a tables:
events[id, 'name', 'date'],
tickets ['id', event_id', 'isAvailable'],
order_tickets ['order_id', 'ticket_id'],
orders['id', 'buyer_id', 'status'].
I need to receive all orders with tickets on the events, where date >= today (do not include tickets to past events.).
My query is next:
$userId = 1;
$orders = Order::with([
'tickets',
'tickets.event',
])->where('buyer_id', $userId)
->where('status', 'sold')
->get();

You can use the whereHas() method and the today() helper function to achieve this:
$orders = Order::with('tickets.event')
->whereHas('tickets.event', function ($query) {
$query->whereDate('date', '>=', today());
})
->where('buyer_id', $userId)
->where('status', 'sold')
->get();

Related

Pluck the values from WITH Eloquent in Laravel

I have a dropdown box that shows only the user with collector and borrower's role. Here's my code
public function create()
{
$users = User::whereHas('roles', function ($q) {
$q->where('roles.name', '=', 'collector')->orWhere('roles.name', '=', 'borrower');
})
->with('profile')
->get()
->pluck('name','id');
return view('dashboard.documents.create', compact('users'));
}
this code is fine but what I what to pluck is the column first_name, last_name and user_id from 'profile'.
How can I achieve that?
Thank you so much in advance!
You do one of these
$users = User::whereHas('roles', function ($q) {
$q->where('roles.name', '=', 'collector')->orWhere('roles.name', '=', 'borrower');})
->with('profile')
->select('name','id')
->get();
Or
$users = User::whereHas('roles', function ($q) {
$q->where('roles.name', '=', 'collector')->orWhere('roles.name', '=', 'borrower');})
->with('profile')
->get(['name','id']);
Both ways will return a collection with related models each model record will has the selected columns, if you want to convert it to an array you can add ->toArray() after the two ways and it will convert the collection to array.

Querying a database relationship with carbon in laravel

I'm trying to select the picture with the most likes from a category the previous day. However, my query returns a null result. My pictures are related to the likes through a has many polymorphic relationship.
Here is my query:
$foodOfTheDay = Picture::withCount('likes')
->where('picture_type', 'food')
->whereHas('likes', function($query) {
$query->whereDate('created_at', Carbon::yesterday());
})
->orderBy('likes_count', 'desc')
->with('user')
->first();
Here is my likeable relationship:
public function likes()
{
return $this->morphMany('App\Like', 'likeable');
}
Thank you for your help.
Try this:
$foodOfTheDay = Picture::withCount('likes')
->where('picture_type', 'food')
->whereHas('likes', function($query) {
$query->whereBetween('created_at', [Carbon\Carbon::yesterday()->startOfDay(), Carbon\Carbon::yesterday()->endOfDay()]);
})
->withCount('likes') // count yesterday's likes
->orderBy('likes_count', 'desc')
->with('user')
->first();
or this:
$foodOfTheDay = Picture::withCount('likes')
->where('picture_type', 'food')
->whereHas('likes', function($query) {
$query->where('created_at', '>=', Carbon::yeserday()->startOfDay())
->where('created_at', '<=', Carbon::yesterday()->endOfDay());
})
->withCount('likes') // count yesterday's likes
->orderBy('likes_count', 'desc')
->with('user')
->first();
Both of them should return picture with the highest likes the previous day (yesterday)
This query selects the picture with most likes without taking into consideration the other days' likes:
$foodOfTheDay = Picture::where('picture_type', 'food')->withCount(['likes' => function($query) {
$query->whereBetween('created_at', [Carbon::yesterday()-
>startOfDay(), Carbon::yesterday()->endOfDay()]);
}])
->orderBy('likes_count', 'asc')
->with('user')
->first();

Laravel eloquent model where datetime less than or equal

I am having an expire_datetime field in Test model and it has many relationship with Candidate model. I want to get all the tests which exipre_datetime is less than or equeal to now datetime. I am doing like this but I am getting all the records, date comparirion is not functioning.
Test Model:
public function testcandidates()
{
return $this->hasMany(Candidate::class,'test_id','id');
}
TestController:
$tests = Test::with([
'testcandidates' => function ($query) {
$query->where('result', '=', 'assigned');
}
])
->where('expire_datetime', '<=', Carbon::now('UTC'))
->get();
Try to get string from carbon: Carbon::now('UTC')->toDateTimeString()
$tests = Test::with(
['testcandidates' => function ($query) {
$query->where('result', '=', 'assigned');
}])
->where('expire_datetime', '<=', Carbon::now('UTC')->toDateTimeString())
->get();

Laravel select only categories wherein product ids

Hi i have a categories and products table with one to many relation. I want to select categories with products which are in product_ids(which it will get from other query). I tried
$categories = Category::with(['products' => function ($query) use($product_ids) {
$query->whereIn('id', $product_ids);
}])
->get();
the above query will select all the categories even if the product not in product_ids ( empty array if not in produc_id) but i just want to select those categories which has the products in the product_ids.please help
I just Solved it by adding whereHas
$categories = Category::with(['products' => function ($query) use($product_ids) {
$query->whereIn('id', $product_ids);
}])
->whereHas('products', function ($q) use($product_ids) {
$q->whereIn('id', $product_ids);
})
->get();
Use whereHas
$categories = Category::whereHas('products', function ($query) use($product_ids) {
$query->whereIn('id', $product_ids);
})
->get();

Excluding pivot rows in Eloquent ORM query

(laravel 4.2)
There are four tables involved; users, posts, flags, and post_flags.
I want to retrieve every post a certain user has, and retrieve the flags set for the post, but only the flags that are set by the user in question.
For example: A post can have flags: 1,2,2,3 where flag 2 is set twice. Once by User A, once by User B. I don't want to see the flags that User B has set.
The Eloquent query in my controller:
$posts = Post::whereHas('companies', function($q) use($company_id) {
$q->where('id', '=', $company_id);
})->with('flags')->get();
The Relation in my Post model:
public function flags() {
return $this->belongsToMany('PostFlag', 'post_postflags', 'post_id', 'flag_id')
->withTimestamps()->withPivot('owner');
}
How would I achieve this using Eloquent ORM?
UPDATE
My final query, thanks to andrewtweber:
Final query
$posts = Post::whereHas('users', function($q) use($id) {
$q->where('id', '=', $id);
})->get()->load([
'flags' => function($query) use($id) {
$query->where('owner', '=', $id)->orWhere('owner', '=', 'SYSTEM');
}
]);
Use wherePivot
http://laravel.com/api/4.2/Illuminate/Database/Eloquent/Relations/MorphToMany.html
$flags = $post->flags()
->wherePivot('user_id', '=', $user_id)
->get();
Or with eager loading
$posts->load([
'flags' => function ($query) use($user_id) {
$query->wherePivot('user_id', '=', $user_id);
}
]);

Resources