Laravel 5.1 How to join two collections of objects - laravel

All warehouses tables have differemt number of columns. So I can't use union inside a query. But I hate this way to join this collection of objects.
There is a better (clear) way?
Thx :)
public function index()
{
$warehouses1 = Farm_warehouse::all();
$warehouses2 = Butchery_warehouse::all();
$warehouses3 = Grape_warehouse::all();
$warehouses4 = Iron_warehouse::all();
$warehouses5 = Rice_warehouse::all();
$warehouses6 = Silk_warehouse::all();
$warehouses7 = Wood_warehouse::all();
$warehouses2 = $warehouses1->merge($warehouses2);
$warehouses3 = $warehouses2->merge($warehouses3);
$warehouses4 = $warehouses3->merge($warehouses4);
$warehouses5 = $warehouses4->merge($warehouses5);
$warehouses6 = $warehouses5->merge($warehouses6);
$warehouses = $warehouses6->merge($warehouses7);
return view('warehouses.index', compact('warehouses'));
}

This may not be the improvement you are looking for but couldn't you chain it together like this?
public function index()
{
$warehouses = Farm_warehouse::all();
$warehouses->merge(Butchery_warehouse::all());
$warehouses->merge(Grape_warehouse::all());
$warehouses->merge(Iron_warehouse::all());
$warehouses->merge(Rice_warehouse::all());
$warehouses->merge(Silk_warehouse::all());
$warehouses->merge(Wood_warehouse::all());
return view('warehouses.index', compact('warehouses'));
}
I think that's a bit easier to read, but may be you can extract it out to a base Warehouse Model or try digging into the Collection class for something more fruitful. Hope this helps.

Related

Refactoring multiple same queries with different value

Is there a better way to refactor this code? It's basically the same line with different values. I thought of doing a for loop but maybe there's another way.
$date = $request->date;
$underConsideration = Application::whereDate('created_at',$date)->where('status','Under consideration')->count();
$phoneScreened = Application::whereDate('created_at',$date)->where('status','Phone screened')->count();
$interviewed = Application::whereDate('created_at',$date)->where('status','Interviewed')->count();
$offerExtended = Application::whereDate('created_at',$date)->where('status','Offer extended')->count();
You should create a separate method for this.
public function myMethod()
{
$under_consideration = $this->fetchApplicationData($request, 'Under consideration');
$phone_screened = $this->fetchApplicationData($request, 'Phone screened');
$interviewed = $this->fetchApplicationData($request, 'Interviewed');
$offer_extended = $this->fetchApplicationData($request, 'Offer extended');
}
private function fetchApplicationData($request, $status)
{
return Application::
whereDate('created_at', $request->date)
->where('status', $status)
->count();
}
That is a much cleaner code.
However, I advise that you should put the items:
Under consideration, Phone screened, Interviewed, Offer extended
into a separate table on the database and just save the status_id on your main table.
One of the major advantage on this is the speed. For example, your client wants to know all record that has a status of Interviewed for a certain date span. Database searching against integer is a lot faster than string.
You could create a method to handle the select operations. Something like:
public function yourExisitingMethod() {
$date = $request->date;
$underConsideration = getData($date,'Under consideration');
$phoneScreened = getData($date,'Phone screened');
$interviewed = getData($date,'Interviewed');
$offerExtended = getData($date,'Offer extended');
}
public function getData($date, $status) {
$data = Application::whereDate('created_at',$date)->where('status',$status)->count();
return $data;
}
This would at the very least improve the maintainability of your code, and in my opinion improves reusability and readability.

How to merge all models in laravel?

I want to show all slideshow when the images are not blank.
public function index()
{
$slideAdvertise = Advertise::whereNotNull('image')->get();
$slideDesignStudio = DesignStudio::whereNotNull('image')->get();
$slideHouse = House::whereNotNull('image')->get();
$slidePhotographer = Photographer::whereNotNull('image')->get();
$slideWebsite = Website::whereNotNull('image')->get();
$slideShows = $slideAdvertise->merge($slideDesignStudio)->merge($slideHouse)->merge($slidePhotographer)->merge($slideWebsite);
return view('Home.index', compact('slideShows'));
}
Note: This code does not even have an error.
There are two things you are missing.
First the all() function at the end of the merge calls.
$slideShows = $slideAdvertise->merge($slideDesignStudio)->merge($slideHouse)->merge($slidePhotographer)->merge($slideWebsite)->all();
Second is to use arrays in case a query returns no results.
public function index()
{
$slideAdvertise = Advertise::whereNotNull('image')->get()->toArray();
$slideDesignStudio = DesignStudio::whereNotNull('image')->get()->toArray();
$slideHouse = House::whereNotNull('image')->get()->toArray();
$slidePhotographer = Photographer::whereNotNull('image')->get()->toArray();
$slideWebsite = Website::whereNotNull('image')->get()->toArray();
$slideShows = $slideAdvertise->merge($slideDesignStudio)->merge($slideHouse)->merge($slidePhotographer)->merge($slideWebsite)->all();
return view('Home.index', compact('slideShows'));
}

carregar mĂșltiplos modelos em um controller

In my Create function, from my products controller. I make several calls to other models that are used to mount combos on the view blade.
$grade = Grade::all();
$marca = Marca::all();
$ncm = Ncm::all();
$clafiscal = Clafiscal::all();
$Otributaria = Origemtributaria::all();
$unidade = Unidade::all();
...
return view('products.create',
compact(
'page',
'etiqueta',
'compCusto',
'grade',
'marca',
'ncm' ,
'clafiscal',
'Otributaria',
'grupo',
'colecao'...);
Is it possible for me to reduce these calls?
I believe there is no other way to compact multiple values.
But, if your problem is related to the dirty controller (with many function calls and responsibilities), you should try to create a more specific method, with will handle this dependencies load and dependencies compact.
Try something like this:
public function loadDependencies()
{
$dependencias = [];
$dependencias['grade'] = Grade::all();
$dependencias['marca'] = Marca::all();
$dependencias['ncm'] = Ncm::all();
$dependencias['clafiscal'] = Clafiscal::all();
$dependencias['Otributaria'] = Origemtributaria::all();
$dependencias['unidade'] = Unidade::all();
return compact($dependencias);
}
public function create()
{
return view('products.create', $this->loadDependencies());
}

How many times the query will hit the database?

Can any one plz optimize the below linq query.It should hit the database only once.
List<LearningItem> items = this.learningitemRepository.GetAll().ToList();
var model = new List<StatementViewerModel>();
foreach (var statement in subjects)
{
var mi = new StatementViewerModel();
mi.UserName = statement.UserName;
mi.SubjectName = statement.Name;
**int nofItems = items.Where(x => x.SubjectId == statement.SubjectId).Count();**
double ratio = (double)statement.AttendedItems / (double)nofItems;
int subjectprogress = (int)(ratio * 100);
mi.Progress = subjectprogress;
model.Add(mi);
}
From what you have posted, your Database should only be being accessed through the GetAll() method of your learmingitemRepository. So if you are worried that you are querying the Database more than once, the GetAll() function is where you should look (assuming your example is not in a function that is being repeatedly called itself).
The rest of your code is iterating over your subjects collection and adding objects to your model collection. There does not appear to be anything in the foreach loop that is accessing your Database.

Magento - get bundled products where a simple product belongs to

I want to show all bundles on a simple product's page and so need to retrieve the information. I searched and tried a lot. This post sounds promising, but is either not working or maybe not for my problem:
Magento - get a list of bundled product ids from a product id
I found a solution for grouped products but this can't be applied here.
$grouped_product_model = Mage::getModel('bundle/product_selection');
$groupedParentId = $grouped_product_model->getParentIdsByChild($product->getId());
I found the table catalog_product_bundle_selection to be the right place to search, but I wonder if there is a clean way and existing function to search this table by product_id than just to hack this.
I didn't find a solution in Mage_Bundle.
What did I miss?
After getting first aid from vrnet I wrote a new block class, so I can update the layout
class Thomaier_Catalog_Block_Product_View_BundledSelect extends Mage_Catalog_Block_Product_View
{
protected $_simpleProducts = array( '3' ); // just an example
public function getBundles() {
$bundleIds = array();
$bundlesCollectionModel = Mage::getResourceModel('bundle/selection_collection');
$bundlesCollection = $bundlesCollectionModel->getSelect()
->where('`selection`.`product_id` in (' . join(',', (array)$this->_simpleProducts) . ')');
foreach ($bundlesCollection as $bundleItem) {
$bundleIds[] = $bundleItem->getParentProductId();
}
...
}
}
I skipped some parts. As I mentioned in the comment, the SQL query works fine when I try it in phpmyadmin, but $bundleItem is not created and ->load() throws an exception.
Thanks for advice.
Below is a method I wrote for a client having the same request with an extra : the ability to shuffle the result.
Hope it helps.
protected $_simpleProducts = array(); // Array with IDs of simple products you want bundles from.
protected $_shuffle = false;
public function getBundles() {
$bundleIds = array();
/*Rather than using a collection model
and make operations with getSelect,
a more elegant way is to extend
Mage_Bundle_Model_Mysql4_Selection_Collection
with a method that would be something like
setProductIdsFilter($productIds)*/
$bundlesCollectionModel = Mage::getResourceModel('bundle/selection_collection');
$bundlesCollection = $bundleCollectionModel->getSelect()
->where('`selection`.`product_id` in (' . join(',', (array)$this->_simpleProducts) . ')');
foreach ($bundlesCollection as $bundleItem) {
$bundleIds[] = $bundleItem->getParentProductId();
}
if (count($bundleIds)) {
$allowBundles = Mage::getResourceModel('catalog/product_collection')
->addIdFilter($bundleIds)
->addFieldToFilter('status', Mage_Catalog_Model_Product_Status::STATUS_ENABLED);
if ($this->_shuffle) {
$allowBundles->getSelect()->order('rand()');
}
if ($allowBundles->count()) {
return $allowBundles;
}
}
return;
The following is the best way to work with these. This way you do not rely on a custom query but instead you can use the core methods:
$bundlesCollection = Mage::getResourceModel('bundle/selection')
->getParentIdsByChild($simple_product_ids_array_or_int);
foreach ($bundlesCollection as $bundleProdId) {
//do anything you want with the bundleProdId array elements
}

Resources