Cannot get parse relation - parse-platform

I have two objects, User and Category with a many-many relationship. Users have a relation column with Categories. There is a user that has a relationship with the Art category. I am trying to retrieve all users with a relationship with the Art category:
var filterByCategory = function(category){
var RelatedUser = Parse.Object.extend("User");
var query = new Parse.Query(RelatedUser);
query.equalTo("categories", category);
query.ascending("username");
query.find({
success: function (results) {
$scope.relatedUsers = results;
$scope.$apply();
},
failure: function (results) {
$scope.relatedUsers = [];
$scope.apply();
}
});
}
category is retrieved from here:
<ul class="category-list">
<li class="category"
data-ng-click="filterByCategory(category)"
data-ng-repeat="category in categories">
{{category.attributes.categoryName}}
</li>
</ul>
There are no results coming back from this request. All users come back if I remove this line:
query.equalTo("categories", category);
The object being sent is definitely a category from my Parse app (I have tested it by specifically pulling the Art category from the "database").

Relations should be queried by 'relation' method
var relation = user.relation("categories");
relation.query().equalTo('', '').find(...)
But it implies you have to have user object already fetched. I am not sure if you can just query 'by relation' :| for all users connected with specific category.

Related

How to query models where relationship is null in Strapi?

I have a model Category with a belongs to many relationship with itself:
Category has many categories in subcategories
Category belongs to one category in supercategory
When I query all categories I get the correct results:
strapi.services.category.find()
When I query all subcategories I also get the correct results:
strapi.services.category.find({ supercategory_null: false })
But when I query just supercategories it doesn't return any categories:
strapi.services.category.find({ supercategory_null: true })
Question
How can I query just the categories that have no supercategory relationship?
This should work
strapi.services.category.find({ supercategory_null: true },['category']);
Defination:
find(params, populate)
populate (array): you have to mention data you want populate e.g ["author", "author.name", "comment", "comment.content"]
The solution I found is to use knex instead of the strapi api:
// Assuming your table name is `category`
const knex = strapi.connections.default;
const categories = await knex(`category`).select(`*`).where(`supercategory`, null);

How to save record in database using belongs to many relation in laravel

I have three tables: restaurant_location, cuisine_restaurant_location and cuisines.
There is a list of all cuisines in my cuisines table. I have all the details of the restaurant in my restaurant_location table. A restaurant can have many cuisines so I made a table cuisine_restaurant_location in which there are two columns cuisine_id and restaurant_id. I have created a belongs to many relation in my restaurant_location model.
restaurant_location model
public function cuisines()
{
return $this->belongsToMany(Cuisine::class, 'cuisine_restaurant_location', 'restaurant_id', 'cuisine_id');
}
I have a form in which all the details of the restaurant along with cuisines is supposed to be added. Right now I am adding all the details of the restaurant. Now the question is how can I insert the cuisines in "cuisine_restaurant_location".
Controller
$rest = new restaurant_location;
$rest->name = $request->input('name');
$rest->description = $request->input('desc');
$rest->save();
$cuisine = new cuisine_restaurant_location
$cuisine_lists = $request->input('cuisines');
foreach ($cuisine_lists as $cuisine_list) {
$cuisine->name = $cuisine_list;
}
You can use the sync and attach methods, described in the Many to many section of the eloquent documentation, for that:
$rest->cuisines()->attach([$cuisineIds])
Where cuisineIds is the list of ids of the cuisines you want to relate.
The difference between sync and attach is that sync will remove all id's not present on the array of ids you are passing.
Try sync() method:
$h = [];
if (isset($input["cuisine_id"])) {
$h = $input["cuisine_id"];
}
$restaurant_location->cuisines()->sync($h);

Query Relational data on Parse

I have seen the other questions relating to querying relational data on parse and they don't quite meet my need.
I have 3 related classes: Teacher (1->many) Course (many<-1) Category
Given the above structure, I want to query for all Instructors who have courses that fall under a certain category. Here is what I have so far:
var Category = Parse.Object.extend("Category");
var category = new Category();
category.id = "shdh43ay";
var Course = Parse.Object.extend("Course"); //There are pointers on Course to both Teacher and Category
var courseQuery = new Parse.Query(Course);
courseQuery.equals('Category', category);
var Teacher = Parse.Object.extend("Teacher");
var teacherQuery = new Parse.Query(Teacher);
teacherQuery.matchesQuery(); //Here is where I am stuck
It doesn't look to me like a matchesQuery would do the trick, any ideas would be welcome

Laravel saving ordered list of eloquent models

I'm creating a food menu which the administrator can order/sort by dragging and dropping. This menu consists of multiple categories (ProductCategory) and products (Product).
I'm using HTML5Sortable on the client-side to allow nested d&d. The markup is pretty simple:
<div class="categories">
#foreach($categories as $category)
<div class="category">
#foreach($category->products as $product)
<div class="products">
<div class=""product" data=id="{{ $product->id }}">
{{ $product->name }}
</div>
</div><!-- /products !-->
#endforeach
</div><!-- /category !-->
#endforeach
</div>
And the corresponding javascript:
$('.categories').sortable({
items: '.category'
});
$('.products').sortable({
items: '.product'
});
// Will be called when the user is done repositioning the products and categories
function getOrderedList() {
var data = {};
$('.categories').find('.category').map(function(i) {
var category = $(this);
data[i] = {};
data[i].id = category.data('id');
data[i].products = category.find('.product').map(function() {
return $(this).data('id');
}).get();
});
data = JSON.stringify(data); // Send data to server
}
The function getOrderedList will send a JSON string back to Laravel, which contains the sorted category id's and product id's:
{"0":{"id":1,"products":[2,3,1,4,5,6,7,8,9,10]},"1":{"id":2,"products":[11,12,13,14]},"2":{"id":3,"products":[15,16,17,18]}}
How would I make this work on the back-end? I guess I must store this array somewhere in the database and later find and order the models by the id's?
In short: What is a clean and flexible solution for sorting (nested) models (within Laravel)?
A common convention is Weight, add a field called (Int)Weight on the products table, which is used to define the order of the items.
Once a change in the order occurs you only update the weight field.
When you retrieve the items, you sort them by Weight.
it becomes similar to an Array
Id Name Weight
01 'product 1' 2
02 'product 2' 0
03 'product 3' 1
when you order it by weight you get
product 2
product 3
product 1
it's similar to an array because
$products[0] = 'product 2'
$products[1] = 'product 3'
$products[2] = 'product 1'
Note that if you want to make it even more dynamic, you can create a polymorphic model that can satisfy multiple models.
Please refer to https://laravel.com/docs/5.1/eloquent-relationships#many-to-many-polymorphic-relations
Polymorphic Relations example
Create table Weights (migration example)
$table->increments('id');
$table->integer('value');
$table->integer('weightable_id')->unsigned();
$table->string('weightable_type');
Create model Weight
class Weight extends Eloquent
{
public function weightable()
{
return $this->morphTo();
}
}
now with any other model
class Products extends Eloquent
{
...
public function weight()
{
return $this->morphOne(Weight::class);
}
}
this way you can just add that method to any model you want then you can sort your model with it.
P.S. make sure any model that uses it, creates that relation immediately after creating the model
i do not recommend this method, it's much better if you explicitly define the weight field in the Products table, i understand how much you want your code to be dynamic, but everything comes at a cost
Performance goes down, it's not easy to visualize your code once you establish polymorphic relations, its more like starting to use Jumps instead of Functions
First, the JSON that you are producing shouldn't be an object where the keys are just array indices. Instead it should be an array of objects that looks like this:
[{"id":1,"products":[2,3,1,4,5,6,7,8,9,10]},{"id":2,"products":[11,12,13,14]},{"id":3,"products":[15,16,17,18]}]
Since the products table to product_categories table has an obvious many to one relationship, you'd just use the product_categories_id foreign key on the products table to represent the relationships laid out in your JSON.
In the nested objects of your JSON, every value in the products key array will have a foreign key that corresponds to the id key value in the same nested object (this is the product_category_id column on your products table).
Your API endpoint function would then look something like this:
public function myApiEndpoint(){
$input = Input::get('input');
$input = json_decode($input, true);
foreach($input as $category){
Product::whereIn('id', $category['products'])->update(array(
'product_category_id' => $category['id']
));
}
}
I am updating the model directly in the API controller here, but you should really do any model changes through a repository that's also implementing an interface.
The above will work if you only ever have one menu (with it's categories and products). If you want multiple menus, then you'll need a menus table along with a three way pivot table (with columns menu_id, product_id, and product_category_id).
I just implement this behavior using this library:
https://github.com/spatie/eloquent-sortable
It is very simple to implement, basically you need an extra column to keep the order and the library will do the rest, here is a part of the documentation:
Implement the Spatie\EloquentSortable\Sortable interface.
Use the trait Spatie\EloquentSortable\SortableTrait.
Optionally specify which column will be used as the order column. The default is order_column.
use Spatie\EloquentSortable\Sortable;
use Spatie\EloquentSortable\SortableTrait;
class MyModel extends Eloquent implements Sortable
{
use SortableTrait;
public $sortable = [
'order_column_name' => 'order_column',
'sort_when_creating' => true,
];
...
}

Parse join table relation

I have the same case that is used in the Parse documentation for many-to-many relations using a join table.
In my case I am fetching a list of users by a simple query, but what I need is to know if current user following the user in the list, meaning I want to add a button to the list of users that allows the current user to follow or unfollow users in the list based on their following status.
Is there any chance that I can get this info with one query?
this will help you. see Relational Queries
var following = Parse.Object.extend("Following"); //Following (ParseObject)
var currentUser = Parse.User.current();
var innerQuery = new Parse.Query(following);
innerQuery.exists("status");
var query = new Parse.Query(currentUser);
query.matchesQuery("follow", innerQuery); //follow is pointer type
query.find({
success: function(comments) {
}
});

Resources