Finding a match in a relation within a query - parse-platform

I've got a Class Users, which has a relation to a class Containers .
I know an Id for the Container object, and i'm trying to figure out if the user has a specific container as a relation.
My code looks like this:
Parse.User.currentAsync().then((myself) => {
// create a relation based on the containers key
var relation = myself.relation('containers');
// generate a query based on that relation
var query = relation.query();
query.equalTo('id', oArgs.container.id);
query.find().then((found) => {
if (found.length > 1) {
deferred.resolve(true);
} else {
deferred.resolve(false);
}
});
});
I always get an empty set of results.
Can anyone help me understand why, and explain what the correct way is of matching a specific object within a relation?
Thanks

Turns out that using
query.equalTo('id', oArgs.container.id);
does not work.
Instead I used this:
query.equalTo('objectId', oArgs.container.id);
And it worked just fine.

Related

Query to pass data to the edit view

I need to pass data to the "edit" view from the "index" view, the data are from two different related tables (table "personas" parent and table "residentes" child) so i'm working in the "edit()" method in the residentesController and i couldn't find a way to pass the data in a single object, is it possible to do it? if there is not What is the best way to do it?
//in the ResidentesController
//this is what i currenly have
public function edit(Residente $residente)
{
$persona = Persona::find($residente->persona_id);
return Inertia::render(
'Residentes/Editar',
[
'residente' => $residente,
'persona' => $persona
]
)
}
If i understand correctly your question you need to load the relationship you need in the original query (keep in mind to create it in the model classes)
$persona = Persona::with('residentes')->find($residente->persona_id);
and after that you can create the variable
$residente = $persona->pluck('residentes');

How to query from database when I have different foreign keys?

I am trying to query data from my database and pass the results to a view called events, the problem I have is that one of my queries will always return the same result because in the where condition the $events_id is the same always. Is there a better way to do the querying? A better logic?
This code is from my controller called EventController:
public function index()
{
$firm_id = DB::table('firms')->where('user_id', auth()->id())->value('id');
$events_id = DB::table('events')->where('firm_id', $firm_id)->value('id');
$events = DB::table('events')->where('firm_id', $firm_id)->get()->toArray();
$actual_events = DB::table('actual_events')->where('event_id', $events_id)->get()->toArray();
return view('events',['events' => $events,'actual_events' => $actual_events]);
}
Since the $events_id is the same every time, the $actual_events will only contain the first result.
The image I have uploaded shows the problem, my table's first three columns are fine. Starting from the fourth they contain repeated values:
As I guess, you need something like this:
$event_ids = DB::table('events')->where('firm_id', $firm_id)->pluck('id');
$actual_events = DB::table('actual_events')->whereIn('event_id', $event_ids)->get()->toArray();
or write about your problem in details and I will try to help you.
you just said that your tables have relation together.
in this case it's better you using the eloquent for that,
first you should type the relations in model of each table like this:
class User extends Authenticatable{
public function cities()
{
return $this->hasmany('App\City'); //you should type your relation
}
}
for relations you can use this link: laravel relationships
after that when you compact the $user variable to your view, you can use this syntax for getting the city value relation to this user: $user->cities;.

Laravel eloquent query with sum of related table

I have a table users and posts with columns user_id and post_views.
In post_views I keep information how many times post was display.
And now, in query I would like to get user with sum of post_views all his posts.
I tried do something like this:
User::where(['id'=>$id])->with('posts')->get();
And in model I defined:
public function posts()
{
return $this->hasMany('App\Models\Post')->sum('post_views','AS','totalViews');
}
But without success.
How to do it?
Thank you
You can use a modified withCount():
public function posts()
{
return $this->hasMany('App\Models\Post');
}
$user = User::withCount(['posts as post_views' => function($query) {
$query->select(DB::raw('sum(post_views)'));
}])->find($id);
// $user->post_views
You can use
User::withCount('posts')->find($id)
to get the user with the id $id and a posts_count attribute in the response
I'm not fully sure what the intention of ->sum('game_plays','AS','totalVies'); is - you would need to add more context if you want this
Just something to add with regards to your shown code: No need to query by id using where + the get() at the end will make you query for a collection. If you want to get a single result use find when searching by id
As always laravel has a method for that : withSum (Since Laravel v8)
Note : I know that at the time of the message was posted, the method did not exist, but since I came across this page when I was looking for the same result, I though it might be interesting to share.
https://laravel.com/docs/9.x/eloquent-relationships#other-aggregate-functions
In your case it should be :
$user = User::withSum('posts as total_views', 'post_views')->find($id);
Then you can access to the result :
$user->total_views

Method on user model to check variable on another table

I have a user model, and I want to check if a user has been assigned a mentor.
public function mentorapplication()
{
return $this->hasMany(mentorApplication::class, 'user_id');
}
public function mentorAssigned()
{
return ($this->mentorapplication()->status == "counsellorAssigned");
}
when I call $user->mentorAssigned() in tinker I get an undefined property for status.
Any ideas?
A couple of things here. Firstly, your relationship is has-many, which is one-to-many. When you try to use the relationship you should expect a Collection to be returned, rather than a single entity. Therefore trying to access the ->status property on returned collection won't work.
Secondly, when you're trying to access the relationship like this:
$this->mentorapplication()
You will get a HasMany instance, which would allow you to chain on more constraints to the query, just like ->where(...), or ->orderBy(...). You would need to use something like ->get() or ->first() to actually run the query and get the results you're after. You can omit the () here and Laravel will load the relation for you, returning your collection:
$this->mentorapplication
Now, I don't know exactly what it is you're trying to achieve, but say for instance you wanted to see if at least one of the mentorApplication objects assigned to the user has a status of counsellorAssigned, you could do something like this:
public function mentorAssigned()
{
foreach ($this->mentorapplication as $mentorapplication) {
if ($mentorapplication->status == 'counsellorAssigned') {
return true;
}
}
return false;
}
Or you could use Laravel's Collection methods to help you rather than just doing a loop here. There are many approaches you could take so I will just leave it there.

Parse.com cloud code dirty relation

I am using Parse Cloud code hooks (beforeSave).
My object has a relation and I need to know which objects where added to this relation.
My problem is exactly the same than here.
I want to be able to do this :
var op = myObject.op('toto');
//Get all add op in relation toto
var added = op.added();
//Get all remove op in relation toto
var deleted = op.removed();
added.forEach(function(pointer) {
//Do something with pointer
//If you need value on pointer
pointer.fetch(function(objectFetched) {
//Do something with object
});
});
}
But that is not working anymore because
Result: TypeError: Object [object Object] has no method 'added'
How can I do now to know which objects was added to the relation ?
Unfortunately there is no information on this in Parse documentation. I had to poke through their source code to figure out how to do the exact thing for my Cloud Code. Anyway, you can get an Array of objectIds that are being added to a Relation like this:
var added = request.object.op("toto").relationsToAdd;
If you want to find the ones being removed, just replace relationsToAdd with relationsToRemove

Resources