Laravel reduce showed Models count - laravel

I am trying to optimize some of my pages. Here is my current situation.
There is one table, where I list all Bookmakers. Here are the columns of the table and their types:
ID (attribute) | Name (attribute) | Games (relation) | Links (relation) ...
1 | Some name | 5 | 10
I have optimized the number of queries by using eager load, unfortunately, on that page, I am loading all relations of each Bookmaker, but I need only the number of each relationship.
Here is my query:
return Bookmaker::select(['*'])->withCount(['links', 'games', 'restrictions', 'licenses', 'favourites'])
->with(['bonuses', 'links', 'games', 'restrictions', 'licenses', 'favourites']);
The debugbar is showing me, that it has loaded also X Bonus models, X Game models, and so on.
How can I disable that load?

Related

How can I remove duplicates results when using belongsToMany

Having the following tables:
----------- ----------------- ---------------
| PROJECT | | ACCESSES | | ENVIRONMENT |
----------- ----------------- ---------------
| id | | id | | id |
| title | | project_id | | title |
----------- | environment_id| ---------------
| username |
| password |
-----------------
My goal is to get all the environments used by a project through the accesses table
In my Project model:
public function environments(){
return $this->belongsToMany('App\Models\Environment', "accesses");
}
My problem is that if I have multiple rows with the same project_id and environment_id values in the accesses table, it will fetch multiple time the same environment.
How may I force it to retrieve each environment only once?
This is an old question, but the benefit of future travellers:
The distinct() method can help in this situation:
public function environments() {
return $this
->belongsToMany('App\Models\Environment', "accesses")
->distinct();
}
From the docs:
The distinct method allows you to force the query to return distinct results:
$users = DB::table('users')->distinct()->get();
As far as I can tell, this works at least as far back as Laravel 4.x, so it should be fine for all currently supported versions.
You can achieve this using sync method or toggle method it depends on your use case.
From the docs:
The many-to-many relationship also provides a toggle method which "toggles" the attachment status of the given IDs. If the given ID is currently attached, it will be detached. Likewise, if it is currently detached, it will be attached:
$project->environments()->toggle([1, 2, 3]);
You may also use the sync method to construct many-to-many associations. The sync method accepts an array of IDs to place on the intermediate table. Any IDs that are not in the given array will be removed from the intermediate table. So, after this operation is complete, only the IDs in the given array will exist in the intermediate table
$project->environments()->sync([1, 2, 3]);
For more information please have a look in the docs.
https://laravel.com/docs/5.6/eloquent-relationships#updating-many-to-many-relationships

How does a multi-column index work in oracle?

I'm building a table to manage some articles:
Table
| Company | Store | Sku | ..OtherColumns.. |
| 1 | 1 | 123 | .. |
| 1 | 2 | 345 | .. |
| 3 | 1 | 123 | .. |
Scenario
Most time company, store and sku will be used to SELECT rows:
SELECT * FROM stock s WHERE s.company = 1 AND s.store = 1 AND s.sku = 123;
..but sometimes the company will not be available when accessing the table.
SELECT * FROM stock s WHERE s.store = 1 AND s.sku = 123;
..Sometimes all articles will be selected for a store.
SELECT * FROM stock s WHERE s.company = 1 AND s.store = 1;
The Question
How to properly index the table?
I could add three indexes - one for each select, but i think oracle should be smart eneugh to re-use other indexes.
Would an Index "Store, Sku, Company" be used if the WHERE-condition has no company?
Would an Index "Company, Store, Sku" be used if the WHERE-condition has no company?
You can think of the index key as conceptually being the 'concatenation' of the all of the columns, and generally you need to have a leading element of that key in order to get benefit from the index. So for an index on (company,store,sku) then
WHERE s.company = 1 AND s.store = 1 AND s.sku = 123;
can potentially benefit from the index
WHERE s.store = 1 AND s.sku = 123;
is unlikely to benefit (but see footnote below)
WHERE s.company = 1 AND s.store = 1;
can potentially benefit from the index.
In all cases, I say "potentially" etc, because it is a costing decision by the optimizer. For example, if I only have (say) 2 companies and 2 stores then a query on company and store, whilst it could use the index is perhaps better suited to not to do so, because the volume of information to be queried is still a large percentage of the size of the table.
In your example, it might be the case that an index on (store,sku,company) would be "good enough" to satisfy all three, but that depends on the distribution of data. But you're thinking the right way, ie, get as much value from as few indexes as possible.
Footnote: There is a thing called a "skip scan" where we can get value from an index even if you do not specify the leading column(s), but you will typically only see that if the number of distinct values in those leading columns is low.
first - do you need index at all? Indexes are not for free. If your table is small enoguh, perhaps you don't need index at all.
Second - what is data structure? You have store column in every scenario - I can imagine situation in which filtering data on store dissects source data to enough degree to be good enough for you.
However if you want to have maximum reasonable performance benefit you need two:
(store, sku, company)
(store, company)
or
(store, company, sku)
(store, sku)
Would an Index "Store, Sku, Company" be used if the WHERE-condition has no company?
Yes
Would an Index "Company, Store, Sku" be used if the WHERE-condition has no company?
Probably not, but I can imagine scenarios in which it might happen (not for the index seek operation which is really primary purpose of indices)
You dissect data in order of columns. So you group data by first element and order them by first columns sorting order, then within these group you group the same way by second element etc.
So when you don't use first element of index in filtering, the DB would have to access all "subgroups" anyway.
I recommend reading about indexes in general. Start with https://en.wikipedia.org/wiki/B-tree and try to draw how it behaves on paper or write simple program to manage simplified version. Then read on indexes in database - any db would be good enough.

Spotfire: Using one selection as a range for another datatable

I've searched quite a bit for this and can't find a good solution anywhere to what seems to me like a normal problem for this product.
I've got a data table (in memory) that is from a rollup table(call it 'Ranges'). Basically like so:
id | name | f1 | f2 | totals
0 | Channel1 | 450 | 680 | 51
1 | Channel2 | 890 | 990 | 220
...and so on
Which creates a bar chart with Name on the X and Totals on the Y.
I have another table that is an external link to a large (500M+ rows) table. That table (call it 'Actuals') has a column ('Fc') that can fit inside the F1 and F2 values of Ranges.
I need a way for Spotfire Analyst (v7.x) to use the selection of the the bar chart for Ranges to trigger this select statement:
SELECT * FROM Actuals WHERE Actuals.Fc between [Ranges].[F1] AND [Ranges].[F2]
But there aren't any relationships (Foreign keys) between the two data sources, one is in memory (Ranges) and the other is dynamic loaded.
TLDR: How do I use the selected rows from one visualization as a filter expression for another visualization's data?
My choice for the workaround:
Add a button which says 'Load Selected Data'
This will run the following code, which will store the values of F1 and F2 in a Document Property, which you can then use to filter your Dynamically Loaded table and trigger a refresh (either with the refresh code or by setting it to load automatically).
rowIndexSet=Document.ActiveMarkingSelectionReference.GetSelection(Document.Data.Tables["IL_Ranges"]).AsIndexSet()
if rowIndexSet.IsEmpty != True:
Document.Properties["udF1"] = Document.Data.Tables["IL_Ranges"].Columns["F1"].RowValues.GetFormattedValue(rowIndexSet.First)
Document.Properties["udF2"] = Document.Data.Tables["IL_Ranges"].Columns["F2"].RowValues.GetFormattedValue(rowIndexSet.First)
if Document.Data.Tables.Contains("IL_Actuals")==True:
myTable=Document.Data.Tables["IL_Actuals"]
if myTable.IsRefreshable and myTable.NeedsRefresh:
myTable.Refresh()
This is currently operating on the assumption that you will not allow your user to view multiple ranges at a time, and simply shows the first one selected.
If you DO want to allow them to view multiple ranges, you can run a cursor through your IL_Ranges table to either get the Min and Max for each value, and limit the Actuals between the min and max, or you can create a string that will essentially say 'Fc between 450 and 680 or Fc between 890 and 990', pass that through to a stored procedure as a string, which will execute the quasi-dynamic statement, and grab the resulting dataset.

Relationship Model in Laravel?

This question is about the Laravel style of doing things:
Everything in Laravel can be done in an elegant way.
I currently have a many to many relationship between mongrels and breeds through a table named breed_mongrel but this table also has a certainty value describing how certain the dog is that he's indeed a mix of that specific breed.
mongrel_id | breed_id | certainty|
----------------------------------
| 1 | 4 | 50 |
| 1 | 2 | 25 |
| 2 | 5 | 75 |
this means that mongrel#1 is 50% sure she's of breed#4 and 25% sure she's also a mix with breed#2. However mongrel#2 is a whooping 75% certain he is breed#5.
My question is what is the elegant way to add records to this table?
I could use something like this:
DB::table('breed_mongrel')->insert(
array('mongrel_id' => 3, 'breed_id' => 5, 'certainty' => 37));
But in Laravel I would normally do things more eloquently like:
$relation = new Relation;
$relation->breed_id = 1;
$relation->save();
But because it is a relationship and I can't follow the normal model named in singular camel caseform and DB table named in plural lower (snail) case I'm not sure what is Laravelly way to add entries to this database table?
You can use attach. It also accepts a second parameter allowing extra values to be added to the pivot table.
$mongrel = Mongrel::find(1);
$breed = Breed::find(4);
$mongrel->breeds()->attach($breed, array('certainty' => '50'));

nested Rowkey in Hbase tables

i have a weather data base with 4 tables : province,city,station, instantHarvestinfo,dailyHarvestInfo
and the relation between tables is parent-child:
(province,city): R(1,m)
(city,station):R(1,m)
(statin,istantharvestInfo):R(1,m)
(station,dailyHarvestInfo):R(1,m)
i want put all of them in one bigtable in hbase and for echa one create a column family..but i dont know how define my row key...i think i need a nested row key that in each step get a split of my rowkey that related a comuln family and give me information of same cf..but how i cant define it?
please help me
there.
I guess you are going to save huge amount of istantharvestInfo and dailyHarvestInfo for each station.
Since there is parent-child relationship in your data model, I think you could
design the schema as:
-------------------------------------------------------------------------
**Row-Key**: Province + city + station + timestamp
--------+---------------------+------------------------------------------
Family | Qualifier | Value
--------+---------------------+------------------------------------------
| istantharvestInfo | "value of istantInfo"
F +---------------------+------------------------------------------
| dailyHarvestInfo | "value of dailyInfo"
--------+---------------------+------------------------------------------
Note that there is only one Family, because we should always make #family as small as possible.

Resources