I have a conceptual problem.
I've defined Many to Many relationship in Firestore. I have 3 collections, A, B and A_B. The A_B collection has documents with IdA_IdB {idA: idA, idB:idB}
What I need is to create and Observable of the documents of B that are related with a
document of A.
I do not know which rxjs operator I need to use or how to. I have tried with switchMap or forEach and MergeMap with no success.
My idea is firstly query the collection A_B using ref.where and pass (idA). Then forEach result query B collection passsing docRef.idB and combine the results in one Observable.
Thanks!
Basically, for a specific document A, docA you want to:
query A_B collection where IdA = docA.Id (let's call results "relation")
for each relation, query DocumentB collection where Id = relation.IdB
return docA with a relatedBs property (DocumentB[])
To accomplish this with rxjs, you can use switchMap, combineLatest and map.
The AngularFire syntax isn't fresh in my mind, but something like this pseudo-code should work:
1 public documentA$ = this.afStore.document(id).pipe(
2 switchMap(docA => this.afStore.collection('A_B').where('idA', '=', docA.id).pipe(
3 switchMap(relations => combineLatest(relations.map(r => this.afStore.document(r.idB)),
4 map(relatedBs => ({...docA, relatedBs}))
))
);
Here's an explanation of the flow:
fetch the DocumentA
switchMap #1 fetches related A_B records
switchMap #2 fetches the collection of related DocumentB documents by using combineLatest to create an observable that emits the collection by mapping each relation to an observable that fetches the corresponding DocumentB
map simply returns the original DocumentA with a relatedBs property appended
Related
I have a challenge that if I want to sort the records when getting using Laravel's ORM based on a list of IDs, how should I do it?!!!!!!!
I mean :
Suppose we have a table called users, which contains 100 records and each record has a unique ID.
We also have an array of IDs.
$ids = [4,1,2,3]
Now I want to get the list of users, but only the users who are first in the ids array and secondly according to the same order as they are listed in this array.
User::whereIn('id' , $Ids)->sortBy('id',$ids)->get();
Can you think of a solution to do this?
User::whereIn('id' , $Ids)->sortBy('id',$ids)->get();
The collections sortBy() function can take a custom call back this way:
$users = User::whereIn('id', $Ids)->get()
->sortBy(function($user, $key) use($ids) {
return array_search($user->id, $ids);
});
This will sort your collection according to the given array.
You can also reference the docs for more information.
Note that the sortBy() function must act upon a collection, which means that the get() function must come before it.
My concern is that while orderBy is applied to the query, I'm not sure how the sortBy is applied?
The reason for using sortBy in my case is because I get the collection via the model (i.e. $user->houses->sortBy('created_at')).
I'm just concerned about the performance: is sortBy simply looping each object and sorting them?, or is Laravel smart enough to simply transform the sortBy into an orderBy executed within the original query?
You need orderBy in order to perform a SQL order.
$user->houses()->orderBy('created_at')->get()
You can also eager load the houses in the right order to avoid N+1 queries.
$users = User::with(['houses' => function ($query) {
return $query->orderBy('created_at');
}])->get();
$orderedHouses = $users->first()->houses;
The sortBy method is applied to the Collection so indeed, it will looping each objects.
The orderBy() method is much more efficient than the sortBy() method when querying databases of a non-trivial size / at least 1000+ rows. This is because the orderBy() method is essentially planning out an SQL query that has not yet run whereas the sortBy() method will sort the result of a query.
For reference, it is important to understand the difference between a Collection object and a Builder object in Laravel.
A builder object is, essentially, an SQL query that has not been run. In contrast, a collection is essentially an array with some extra functionality/methods added. Sorting an array is much less efficient than pulling the data from the DB in the correct format on the actual query.
example code :
<?php
// Plan out a query to retrieve the posts alphabetized Z-A
// This is still a query and has not actually run
$posts = Posts::select('id', 'created_at', 'title')->orderBy('title', 'desc');
// Now the query has actually run. $posts is now a collection.
$posts = $posts->get();
// If you want to then sort this collection object to be ordered by the created_at
timestamp, you *could* do this.
// This will run quickly with a small number or rows in the result,
// but will be essentially unusable/so slow that your server will throw 500 errors
// if the collection contains hundreds or thousands or objects.
$posts = $posts->sortBy('created_at');
I am new to laravel and confused about some query methods.
find($id) is useful and returns a nice array, but sometimes I need to select by other fields rather than id.
The Laravel document said I could use where('field', '=', 'value') and return a bunch of data, which is fine.
What I can't understand is why I need to add ->first() every time, even if I am pretty sure there is only one single row matches the query.
It goes like this:
$query->where(..)->orderBy(..)->limit(..) etc.
// you can chain the methods as you like, and finally you need one of:
->get($columns); // returns Eloquent Collection of Models or array of stdObjects
->first($columns); // returns single row (Eloquent Model or stdClass)
->find($id); // returns single row (Eloquent Model or stdClass)
->find($ids); // returns Eloquent Collection
// those are examples, there are many more like firstOrFail, findMany etc, check the api
$columns is an array of fields to retrieve, default array('*')
$id is a single primary key value
$ids is an array of PKs, this works in find method only for Eloquent Builder
// or aggregate functions:
->count()
->avg()
->aggregate()
// just examples here too
So the method depends on what you want to retrieve (array/collection or single object)
Also the return objects depend on the builder you are using (Eloquent Builder or Query Builder):
User::get(); // Eloquent Colleciton
DB::table('users')->get(); // array of stdObjects
even if I am pretty sure there is only one single row matches the query.
Well Laravel cant read your mind - so you need to tell it what you want to do.
You can do either
User::where('field', '=', 'value')->get()
Which will return all objects that match that search. Sometimes it might be one, but sometimes it might be 2 or 3...
If you are sure there is only one (or you only want the first) you can do
User::where('field', '=', 'value')->first()
get() returns an array of objects (multiple rows)
while
first() returns a single object (a row)
You can of course use get() when you know it will return only one row, but you need to keep that in mind when addressing the result:
using get()
$rez = \DB::table('table')->where('sec_id','=','5')->get();
//will return one row in an array with one item, but will be addressed as:
$myfieldvalue = $rez[0]->fieldname;
using first()
$rez = \DB::table('table')->where('sec_id','=','5')->first();
// will also return one row but without the array, so
$myfieldvalue = $rez->fieldname;
So it depends on how you want to access the result of the query: as an object or as an array, and also depends on what "you know" the query will return.
first() is the equivalent of LIMIT 1 at the end of your SELECT statement. Even if your query would return multiple rows, if you use first() it will only return the first row
Background
I have a List model which belongs to and has many Subscriber. And of course a Subscriber which belongs to and has many List.
Problem
I want to eager-load all subscribers from multiple lists. BUT, I am only interested in distinct subscribers, since a subscriber can have and indeed belong to multiple lists.
My attempt
I have used the distinct() method but this hasn't yielded any joy. And I can also loop through the result set to manually slice out duplicates. Just wondering if there is a way of letting Laravel do the dirty job for me?
Code
$lists = Input::get('listsarray');
$addresses = Addressbook::with(array('subscribers' => function($query)
{
$query->where('active', '=', 1);
// $query->distinct(); //This didn't work
}))->whereIn('id', $lists)->get();
Retrieving unique subscribers through join
I'll try my best to explain it using Lists instead of Adressbook, because I couldn't really understand your model and that may introduce further confusion.
If I understood your comments correctly, you are trying to retrieve all unique subscribers that have associations with lists of id IN listarray. In that case, Eager Loading is not the proper way of doing that. Eager loading serves the purpose of pre-loading associations for a model, in order to use them later on. In your case, you are not retrieving Lists and their Subscribers, but rather the unique Subscribers themselves.
$lists = Input::get('listsarray');
$subscribers = Subscriber::join('list_subscriber', 'list_subscriber.subscriber_id', '=', 'subscribers.id')
->whereIn('list_subscriber.list_id', $lists)
->groupBy('list_subscriber.subscriber_id')
->get(array('subscribers.*'));
If you also wish to retrieve all lists associated with such subscribers, you can do so:
// Simply include a with('lists') and Eloquent will eager load them
$subscribers = Subscriber::with('lists')
->join('list_subscriber', 'list_subscriber.subscriber_id', '=', 'subscribers.id')
->whereIn('list_subscriber.list_id', $lists)
->groupBy('list_subscriber.subscriber_id')
->get(array('subscribers.*'));
Eager Loading
If it's a matter of simply improving performance, you don't need to use distinct, Laravel already does it. Eloquent behaves like this:
Fetchs all lists.
Iterates through lists building an array of unique list_ids
Fetchs all list_subscribers using WHERE list_id IN (X, Y, Z)
Iterates through all list_subscribers building an array of unique subscriber_id
Fetchs all subscribers using WHERE id IN (X, Y, Z)
I'm confused as to when ->get() in Laravel...
E.G. DB::table('users')->find(1) doesn't need ->get() to retrieve the results, neither does User::find(1)
The laravel docs say "...execute the query using the get or first method..."
I've read the Fluent Query Builder and Eloquent docs but don't understand when the usage of get() is required...
Thanks for the help
Since the find() function will always use the primary key for the table, the need for get() is not necessary. Because you can't narrow your selection down and that's why it will always just try to get that record and return it.
But when you're using the Fluent Query Builder you can nest conditions as such:
$userQuery = DB::table('users');
$userQuery->where('email', '=', 'foo#bar.com');
$userQuery->or_where('email', '=', 'bar#foo.com');
This allows you to add conditions throughout your code until you actually want to fetch them, and then you would call the get() function.
// Done with building the query
$users = $userQuery->get();
For find(n), you retrieve a row based on the primary key which is 'n'.
For first(), you retrieve the first row among all rows that fit the where clauses.
For get(), you retrieve all the rows that fit the where clauses. (Please note that loops are required to access all the rows or you will get some errors).
find returns one row from the database and represent it as a fluent / eloquent object. e.g. SELECT * FROM users WHERE id = 3 is equivalent to DB::table('users')->find(3);
get returns an array of objects. e.g. SELECT * FROM users WHERE created_at > '2014-10-12' is equivalent to DB::table('users')->where('created_at', '>', '2014-10-12')->get() will return an array of objects containing users where the created at field is newer than 4014-10-12.
The get() method will give you all the values from the database that meet your parameters where as first() gets you just the first result. You use find() and findOrFail() when you are searching for a key. This is how I use them:
When I want all data from a table I use the all() method
Model::all();
When I want to find by the primary key:
Model::find(1)->first();
Or
Model::findOrFail(1)->first();
This will work if there is a row with a primary key of one. It should only retrieve one row so I use first() instead of get(). Remember if you deleted the row that used key 1, or don't have data in your table, your find(1) will fail.
When I am looking for specific data as in a where clause:
Model::where('field', '=', 'value')->get();
When I want only the first value of the data in the where clause.
Model::where('field', '=', 'value')->first();
Basically what you need to understand is that get() return a collection(note that one object can be in the collection but it still a collection) why first() returns the first object from the result of the query(that is it returns an object)
#Take_away
Get() return a collection first() return an object
You can use get() method with latest() method to get the latest record that were recently added to your table
For example
$user=Student::latest()->get();
return all the data in descending order