Reputation: 513
I want to use a model to query data so I am defining the model relations like this:
In Categories
$this->hasManyToMany(
"id",
"App\\Models\\CategoriesContents",
"category_id",
"content_id",
"App\\Models\\Contents",
"id",
["alias" => "contents"]
);
In CategoriesContents
$this->belongsTo(
"category_id",
"App\\Models\\Categories",
"id",
["alias" => "category"]
);
$this->belongsTo(
"content_id",
"App\\Models\\Contents",
"id",
["alias" => "content"]
);
In Contents
$this->hasManyToMany(
"id",
"App\\Models\\CategoriesContents",
"content_id",
"category_id",
"App\\Models\\Categories",
"id",
["alias" => "categories"]
);
I have to order by name, the name in the contents table and I have a condition in the category table.
Does anyone know how to query a relation with a default where
and order by
clause?
Upvotes: 2
Views: 888
Reputation: 513
I have the solution but I don't think it the best way I add this function in contents model
public function find_extended($paramsMain, $paramsRelated, $limit=30, $offset=10)
{
//Define output
$outputs = [];
$index = 0;
$contents = self::find($paramsMain);
foreach($contents as $content)
{
$contentData = $content->toArray();
$categories = $content->getCategories($paramsRelated)->toArray(); // use above parameters to search and sort as you wish
if (!empty($categories)) {
$contentData["categories"] = $categories;
if ($index >= ($limit+$offset)) {
return $outputs;
}
if ($index >= $offset) {
$outputs[] = $contentData;
}
$index++;
}
}
return $outputs;
}
Upvotes: 0
Reputation: 3884
Here is a full example of relation with custom parameters:
$this->hasMany('id', 'Models\News', 'category_id', [
'alias' => 'news',
'reusable' => true,
'params' => [
'order' => 'id ASC',
'conditions' => 'is_active = :is_active:',
'bind' => [
'is_active' => 1
]
]
]);
There are more ways in the documentation.
Your first relation with ordering and where clause would look like this:
$this->hasManyToMany(
"id",
"App\\Models\\CategoriesContents",
"category_id",
"content_id",
"App\\Models\\Contents",
"id",
[
"alias" => "contents",
"params" => [
'order' => 'App\\Models\\Contents.title ASC',
'conditions' => 'condition = :conditionParam:',
'bind' => [
'conditionParam' => $something
]
]
]
);
Upvotes: 1