Getting null array PHP - php

i have a database named "products" which has a column "categories". This table contain four category of products namely electronic,Decoration,clothes and vehicle. My target to show these category with their count ie:if there are four products belongs to category electronic, then output should be like this :electronic=4 and so on
My code
public function category()
{
$arrayCategorys = ['electronic','Decoration','clothes','vehicle'];
$data = [];
foreach($arrayCategorys as $arrayCategory)
{
$sql = "SELECT count(id) FROM products WHERE categories='$arrayCategory'";
$records = \DB::select($sql);
$data = array_merge_recursive($data, [
"{$arrayCategory}" =>isset($records[0]->count),
]);
$data=array_filter($data);
dd($data);
}
}
I want show output like this
'electronic'=>'4',
'Decoration'=>'2',
'clothes'=>'2',
'vehicle'=>'1' according to data in database
but iam getting nothing ,[]

You can GROUP BY your categories like this way when you COUNT
SELECT categories,COUNT(*)
FROM products
GROUP BY categories;
For Idea: http://www.w3resource.com/mysql/aggregate-functions-and-grouping/aggregate-functions-and-grouping-count-with-group-by.php
EDIT: Though i am not familiar with laravel5 syntax but this may work for you
$result = DB::table('products')
->select('products.categories',
DB::raw('count(products.id) as category_count')
)
->orderBy('products.id', 'asc')
->groupBy('products.categories')
->get();

You used isset($records[0]->count) but the column name for the count will be count(id). Name the count as count like this "SELECT count(id) AS count FROM products WHERE categories='$arrayCategory'". And you wont be able to get the count just by checking if it is set. Remove the isset and just use $records[0]->count. The code should look like:
public function category()
{
$arrayCategorys = ['electronic','Decoration','clothes','vehicle'];
$data = [];
foreach($arrayCategorys as $arrayCategory)
{
$sql = "SELECT count(id) AS count FROM products WHERE categories='$arrayCategory'";
$records = \DB::select($sql);
$data = array_merge_recursive($data, [
"{$arrayCategory}" =>$records[0]->count,
]);
$data=array_filter($data);
dd($data);
}
}

Related

Laravel table joins

I'm trying to do some table joins and having some trouble.i need to display
the customer’s complete name and title, item description, quantity ordered, for each item ordered after April 2000. i made a SQL script that works but i need to use Laravel ORM.
SELECT `first_name`,`last_name`,o.order_id,`quantity`,`description`,`date_placed`
FROM `customer` c
JOIN `order` o
ON c.`customer_id` = o. `customer_id`
JOIN `orderline` ol
ON o.`order_id` = ol. `order_id`
JOIN `item` i
ON ol.`item_id` = i. `item_id`
WHERE `date_placed` > '2000-4-00';
I created 2 models for the tables "Customer", "Order"
here is my Customer model
public function orders(){
return $this->hasMany('App\Order','customer_id');
}
here is my order model
public function orderline(){
return $this->hasMany('App\Orderline','order_id');
}
right now i am able to get some of my data but i dont feel like this is a good way to go about
$customer = Customer::all();
foreach($customer as $input){
$item = Customer::find($input->customer_id)->orders;
$name = $input->title . ' ' . $input->first_name . ' ' . $input->last_name;
$datePlaced = null;
$orderID = null;
foreach($item as $value){
$orderID = $value->order_id;
$datePlaced = $value->date_placed;
$order = Order::find($value->order_id)->orderline;
}
if anyone could point me in the right direction that would be great.
It looks like you want to get all Customers with their Orders and OrderLines?
Customer::with(['order' => function ($query) {
$query->where('date_placed', '>=', '2000-04-01')->with('orderline');
}])->get();
If you want to limit the columns on the relationships, you can...
Customer::with(['order' => function ($query) {
$query->select(/* columns */)->where('date_placed', '>=', '2000-04-01')
->with(['orderline' => function ($query) {
$query->select(/* columns here */);
}]);
}])->get();
Just make sure if you specify the columns in the relationships, that you're selecting all of the foreign keys or related columns for each relationship.

Cannot get relation in Laravel pivot tables

I want to build relations between three tables in laravel. Currently i have three models
Classroom,
public function subjects(){
return $this->belongstoMany('Subject','subject_section_classroom');
}
Section,
Subject
My Tables are
classrooms(id, name)
sections(id, name)
subjects(id, name)
subject_section_classroom( id, classroom_id, section_id, subject_id)
In my classroomsController I have
public function assignsubjects($class_id, $section_id){
$classroom = Classroom::find($class_id);
$section = Section::find($section_id);
$subjects = Subject::lists('name','id');
$selected_subjects = $classroom->subjects()->where('section_id', '=', 1);
$subjects = Subject::lists('name','id');
return view('assignedit', compact('classroom','section','subjects', 'selected_subjects'));
}
But I can't get the selected_subjects from above relation. And when I tried to get the sql of the above query (with ->toSQL()), I get
`"select * from `myschool_subjects` inner join `myschool_subject_section_classroom` on `myschool_subjects`.`id` = `myschool_subject_section_classroom`.`subject_id` where `myschool_subject_section_classroom`.`classroom_id` = ? and `section_id` = ?"`
I can't figure what I am doing wrong here.
Please Help.
I think your problem is coming from
php
$selected_subjects = $classroom->subjects()->where('section_id', '=', 1);
Change it to:
php
$selected_subjects = $classroom->subjects()->where('section_id', '=', 1)->get();

How to fetch data with pivot table using where condition on pivot in laravel4

How can I fetch data with belongsToMany relation models.
Table tags
- id
- name
...
Table photo_entries
- id
...
Table photo_entry_tag
- id
- tag_id
- photo_entry_id
Tag.php
public function photo_entry()
{
return $this->belongsToMany('PhotoEntry');
}
PhotoEntry.php
public function tags()
{
return $this->belongsToMany('Tag');
}
Now I need to fetch photo entries from photo_entries table with their tags where tag_id=1.
I have tried this:
$photos = PhotoEntry::orderBy('votes', 'desc')->with(array('tags' => function($query)
{
$query->where('tag_id', 1);
}))->paginate(50);
But its not giving me the proper result, its returning all photos. I am not getting what is the issue.
Can any one please help me.
You need to select all records form photo_entries table that has a relation in photo_entry_tag table so to do that your query should be like this
$tag_id = 1;
$query = "SELECT * FROM `photo_entries` WHERE `id` IN (SELECT `photo_entry_id` FROM `photo_entry_tag` WHERE `tag_id` = {$tag_id})";
Also the equivalence code in eloquent will be like the code below
$tag_id = 1;
$photos = PhotoEntry::whereIn('id', function($query) use ($tag_id) {
$query->select('photo_entry_id')->from('photo_entry_tag')->whereTagId($tag_id
);
})->get();
Also you can add orderBy('votes', 'desc') just before get() to sort the result

Getting data from 2 tables in magento

I created 2 textension in magento along with 2 different tables. First extension store data in table-1 while second second extension store data in table-2. Now i want to display data in first extension by LeftJoin. It show data without leftjoin from first table but not showing data with leftjoin from both the tables.
This code in block.php
public function methodblock()
{
$collection = Mage::getModel('test/test')->getCollection();
$returnCollection = $collection->getSelect()
->joinLeft('magento_answer', 'id_pfay_test=question_id',
array('*'), null , 'left');
return $returnCollection;
}
On Layout side. dislplaydata.phtml
<?php
$collection = $this->testmethodblock();
foreach($collection as $rows {
echo $rows ->getData('name');
}
I Got the answer. I use the custom query which works for me.
$resource = Mage::getSingleton('core/resource');
$readConnection = $resource->getConnection('core_read');
$qTable = $resource->getTableName('pfay_test');
$aTable = $resource->getTableName('answer/answer');
$query = 'SELECT * FROM '.$qTable.' q left join '.$aTable.' a ON a.question_id=q.id_pfay_test';
$results = $readConnection->fetchAll($query);
return $results;

Select posts based on selected categories

I have following scenario:
user selects couple categories
user should see posts which belongs to these categories
post belong to one or more categories
I setup the database like this:
users -> category_user <- categories
posts -> categoriy_post <- categories
I managed to accomplish this, but I had to find all ids from these tables to find relevant posts. I need to make it simpler because this approach is blocking some other actions I need to do. This is my code:
$categoryIds = Auth::user()->categories;
$ids = array();
$t = array_filter((array)$categoryIds);
if(!empty($t)){
foreach ($categoryIds as $key => $value) {
$ids[] = $value->id;
}
}else{
return View::make("main")
->with("posts", null)
->with("message", trans("front.noposts"))->with("option", "Latest");
}
$t = array_filter((array)$ids);
if(!empty($t)){
$p = DB::table("category_post")->whereIn("category_id", $ids)->get();
}else{
return View::make("main")
->with("posts", null)
->with("message", trans("front.noposts"))->with("option", "Latest");
}
$postsIds = array();
foreach ($p as $key => $value) {
$postsIds[] = $value->post_id;
}
$t = array_filter((array)$postsIds);
if(!empty($t)){
$postIds = array_unique($postsIds);
$posts = Post::whereIn("id", $postsIds)
->where("published", "=", "1")
->where("approved", "=", "1")
->where("user_id", "!=", Auth::user()->id)
->orderBy("created_at", "desc")
->take(Config::get("settings.num_posts_per_page"))
->get();
return View::make("main")
->with("posts", $posts)->with("option", "Latest");
}else{
return View::make("main")
->with("posts", null)
->with("message", trans("front.noposts"))->with("option", "Latest");
}
How to do this properly without this bunch code?
Yes, there is Eloquent way:
$userCategories = Auth::user()->categories()
->select('categories.id as id') // required to use lists on belongsToMany
->lists('id');
if (empty($userCategories)) // no categories, do what you need
$posts = Post::whereHas('categories', function ($q) use ($userCategories) {
$q->whereIn('categories.id', $userCategories);
})->
... // your constraints here
->get();
if (empty($posts)) {} // no posts
return View::make() ... // with posts
Or even better with this clever trick:
$posts = null;
Auth::user()->load(['categories.posts' => function ($q) use (&$posts) {
$posts = $q->get();
}]);
if (empty($posts)) // no posts
return View... // with posts
Obviously, you can write joins, or even raw sql ;)
You can take those categories directly from the database from user records:
SELECT ...
FROM posts AS p
INNER JOIN category_post AS cp ON cp.id_post = p.id
INNER JOIN categories AS c on c.id = cp.id_category
INNER JOIN category_user AS cu ON cu.id_category = c.id
WHERE cu.id_user = 123 AND p.published = 1 AND ...
Joins in Laravel can be achieved, see the documentation: laravel.com/docs/queries#joins Maybe there is also an Eloquent way, I don't know, try searching :-)

Categories