Getting trouble in writing query laravel - laravel

Can anyone help me to get the data .
$ticketList = Ticket::with('appliance', 'brand')->get();
$userAppliances = DB::table('user_appliances')
->where('user_id', 5)
->pluck('appliance_id')
->toArray();
$userBrands = DB::table('user_brands')
->where('user_id', 5)
->pluck('brand_id')
->toArray();
$ticketList = $ticketList->map(function ($ticket) use ($userAppliances) {
return $ticket->where($ticket->appliance_id,'=', $userAppliances);
});
dd($ticketList);
It returnd the collection. I want all the tickets, where ticket->brand_id and tickt->appliance_id includes {all the id i am getting in array from userBrands and userAppliances}. I am getting trouble in writing query

Try it out this
$userBrands = DB::table ('user_brands')
->where('user_id', 5)
->pluck('appliance_id')
->toArray();
$ticketList = Ticket::with('appliance', 'brand')
->where(function($query) use ($userBrands){
$query->whereIn('appliance_id', $userBrands);
})->get();

Related

laravel does not exist on this collection instance

$orders = Orders::select('orders.id as order_id', 'collection_color.color_name as color', 'collection_color.id as collection_color_id', DB::raw('SUM(order_piece.piece) As piece'))
->join('order_piece', 'order_piece.order_id', '=', 'orders.id')
->join('collection_color_size_barcode', 'collection_color_size_barcode.id', '=', 'order_piece.collection_color_size_barcode_id')
->join('collection_color', 'collection_color.id', '=', 'collection_color_size_barcode.collection_color_id')
->whereIn('orders.id', $request->order_id)
->groupBy('order_piece.order_id')
->orderBY('orders.delivery_date', 'ASC')
->get();
return $orders; => [{"order_id":30,"color":"Kahverengi","collection_color_id":21,"piece":"500"}]
return $ccfc = CollectionColorFabricColor::whereIn('collection_color_id', $orders->collection_color_id)->get();
Property [collection_color_id] does not exist on this collection instance. i am getting error can you help me
The error is most likely due to this in your second code snippet: $orders->collection_color_id. $orders is a collection, so the property doesn't exist in that object. What you actually need is to pluck those values from that collection like so:
return $ccfc = CollectionColorFabricColor::query()
->whereIn('collection_color_id', $orders->pluck('collection_color_id'))
->get();
Because your $orders is collection, you need to get collection_color_id array like this :
$arrayColors = $orders->pluck('collection_color_id')->toArray();
then
return $ccfc = CollectionColorFabricColor::whereIn('collection_color_id', $arrayColors)->get();

Convert mysql query into query builder

Hello Guys I am new with the query builder of laravel.
I want to convert this query into laravel query builder. Thank you in advance.
$bo_facilities = ' SELECT
a.bo_facility_code,
a.bo_facility_groupcode,
a.bo_number,
a.bo_indYesOrNo,
a.bo_indLogic,
b.bo_content_facility_description
FROM
bo_facilities AS a
RIGHT JOIN bo_content_facilities AS b
ON b.bo_content_facility_code = a.bo_facility_code AND b.bo_content_facility_facilityGroupCode = a.bo_facility_groupcode
WHERE a.bo_hotel_code = "1" GROUP BY b.bo_content_facility_description';
My groupBy method didnt work..
$join->groupBy('b.bo_content_facility_description');
this is my whole code
I didn't know the best way.
DB::table('bo_facilities AS a')
->select("a.bo_facility_code", "a.bo_facility_groupcode", "a.bo_number", "a.bo_indYesOrNo", "a.bo_indLogic", "b.bo_content_facility_description")
->join('bo_content_facilities AS b', function ($join) {
$join->on('b.bo_content_facility_code', '=', 'a.bo_facility_code');
$join->on('b.bo_content_facility_facilityGroupCode', '=', 'a.bo_facility_groupcode');
$join->groupBy('b.bo_content_facility_description');
})
->where('a.bo_hotel_code', $hotelCode)
->get();
Finally I already fixed my problem.
$bo_facilities_raw = DB::table('bo_facilities AS a')
->join('bo_content_facilities AS b', function ($join) {
$join->on([['b.bo_content_facility_code', '=', 'a.bo_facility_code'], ['b.bo_content_facility_facilityGroupCode', '=', 'a.bo_facility_groupcode']]);
})
->select("a.bo_hotel_code","a.bo_facility_code", "a.bo_facility_groupcode", "a.bo_number", "a.bo_indYesOrNo", "a.bo_indLogic", "b.bo_content_facility_description", "b.bo_content_facility_code", "b.bo_content_facility_facilityGroupCode")
->where('a.bo_hotel_code', 1)
->get();
$bo_facilities_decode = json_decode($bo_facilities_raw, true);
$remove_dupli = array_unique(array_column($bo_facilities_decode, 'bo_content_facility_description'));
$bo_facilities = array_intersect_key($bo_facilities_decode, $remove_dupli);
the duplication of records was inside the multidimensional array thats why i use array unique and array intersect key for removing the duplicate descriptions.

Laravel nested whereIn from multiple tables

I'm using Laravel 5.7. How do i rewrite below code as a single nested query?
I'm currently fetching the result using 2 database queries. I go through some of the answers in stackoverflow, but i still have doubts in nesting multiple tables
$connectedParts = DB::table('part_connections as c')
->join('parts_master as p', 'p.id', '=', 'c.part_number_id')
->where('c.part_number_id', $partId)
->where('p.id', $partId)
->pluck('connected_to');
$connectedComponents = DB::table('part_connections as pc')
->join('parts_master as pm', 'pm.id', '=', 'pc.connected_to')
->where('part_number_id',$partId)
->where('pm.part_type','1')
->whereIn('connected_to', $connectedParts)
->pluck('connected_to');
Any help would be greatly appreciated.
Set your relationship properly in your model first then try this query:
//PartConnection model - add for eager loading
public function master() {
return $this->belongsTo('PartMaster::class', 'connected_to', 'id');
}
$query = PartConnection::whereHas(‘master’, function($qry)) use ($partId) {
$qry->where(‘parts_master.id’, $partId);
$qry->where(‘parts_master.part_type’, 1);
});
$query->where(‘part_number_id’, $partId);
$connectedComponents = $query->get();
update
Try this then:
$connectedComponents = DB::table('part_connections as pc')
->join('parts_master as pm', function($join) {
$join->on('pc.connected_to', '=', 'pm.id');
$join->on('pc.part_number_id', '=', 'pm.id');
}) //updated this - removed ;
->where('part_number_id',$partId)
->where('pm.part_type','1')
->get();

problems with sequence code in controller

The $trendtag code alone works. However it doesnt get posts if I want to load the posts.
If I run dd($tagIdArray), I get the id's of the tags. But the following code has no function. If I do not use $trendtags, or only like this, it works:
$trendtags = Taggable::take(3)
->with('tag')
->get();
But how can I find the most used tags in the last 48 Hours?
Is there another way?
$trendtags = Taggable::whereDate('created_at', '>=', now()->subHours(48))
->groupBy('tag_id')
->orderByRaw('count(tag_id) DESC')
->take(3)
->with('tag')
->get();
$tagIdArray = $trendtags->pluck('id')->all();
$article = Article::with('comments', 'tags')
->whereIn('privacy', [1, 2])
->where('status', 1)
->whereHas('tags', function($query) use ($tagIdArray) {
$query->whereIn('id', $tagIdArray);
}, '>=', count($tagIdArray))
->latest()
->paginate(15);

Laravel eloquent and relationship

I have a code:
$response = $this->posts
->where('author_id', '=', 1)
->with(array('postComments' => function($query) {
$query->where('comment_type', '=', 1);
}))
->orderBy('created_at', 'DESC')
->limit($itemno)
->get();
And when I logged this query with:
$queries = \DB::getQueryLog();
$last_query = end($queries);
\Log::info($last_query);
In log file I see follow:
"select * from `post_comments` where `post_comments`.`post_id` in (?, ?, ?, ?) and `comment_type` <> ?"
Why is the question mark for comment_type in the query?
Update #1:
I replaced current code with following and I get what I want. But I'm not sure it is OK. Maybe exists many better, nicer solution.
$response = $this->posts
->where('author_id', '=', 1)
->join('post_comments', 'post_comments.post_id', '=', 'posts.id')
->where('comment_type', '=', 1)
->orderBy('created_at', 'DESC')
->limit($itemno)
->get();
Behind the scene the PDO is being used and it's the way that PDO does as a prepared query, for example check this:
$title = 'Laravel%';
$author = 'John%';
$sql = "SELECT * FROM books WHERE title like ? AND author like ? ";
$q = $conn->prepare($sql);
$q->execute(array($title,$author));
In the run time during the execution of the query by execute() the ? marks will be replaced with value passed execute(array(...)). Laravel/Eloquent uses PDO and it's normal behavior in PDO (PHP Data Objects). There is another way that used in PDO, which is named parameter/placeholder like :totle is used instead of ?. Read more about it in the given link, it's another topic. Also check this answer.
Update: On the run time the ? marks will be replaced with value you supplied, so ? will be replaced with 1. Also this query is the relational query, the second part after the first query has done loading the ids from the posts table. To see all the query logs, try this instead:
$queries = \DB::getQueryLog();
dd($queries);
You may check the last two queries to debug the queries for the following call:
$response = $this->posts
->where('author_id', '=', 1)
->with(array('postComments' => function($query) {
$query->where('comment_type', '=', 1);
}))
->orderBy('created_at', 'DESC')
->limit($itemno)
->get();
Update after clarification:
You may use something like this if you have setup relation in your Posts model:
// $this->posts->with(...) is similar to Posts::with(...)
// if you are calling it directly without repository class
$this->posts->with(array('comments' =. function($q) {
$q->where('comment_type', 1);
}))
->orderBy('created_at', 'DESC')->limit($itemno)->get();
To make it working you need to declare the relationship in your Posts (Try to use singular name Post if possible) model:
public function comments()
{
return $this->hasmany('Comment');
}
Your Comment model should be like this:
class Comment extends Eloquent {
protected $table = 'post_comments';
}

Resources