I have the given table structure:
// table: examples
+ -- + ---- +
| id | name |
+ -- + ---- +
| 1 | Test |
| 2 | Test |
+ -- + ---- +
// table: example_data
+ -- + --------------- + ------------------ + --- + ----------------- +
| id | example_data_id | exmaple_data_type | key | value |
+ -- + --------------- + ------------------ + ------------|---------- +
| 1 | 1 | App\Models\Example | external | 1 |
| 2 | 1 | App\Models\Example | otherKey | string |
| 3 | 2 | App\Models\Example | external | 0 |
+ -- + --------------- + ------------------ + ----------- + --------- +
// Example Model:
public function daten()
{
return $this->morphMany(ExampleData::class, 'example_data');
}
// ExampleData Model:
public function example_data()
{
return $this->morphTo();
}
How I can order my examples by "value" in "example_data" with key = "external"?
$examples = Example::with('daten')
->orderBy(***value from external in daten***) // something like this 'Example->daten->key="external" ==> orderBy Example->daten->value'
->paginate($request->total);
Is it possible with orderBy and callback? How is the callback?
Does this answer your question:
$examples = Example::with(['daten' => function($query) {
$query->orderBy('key', 'asc');
}])
->paginate($request->total);
This will order the key column by ascending.
If you want only records where key is equal to external you can do this:
$examples = Example::with(['daten' => function($query) {
$query->where('key', 'external');
$query->orderBy('value', 'desc');
}])
->paginate($request->total);
And sort it by the value column.
Related
Learner | AssesmentId | Attempt
------------------------------------
Parker | 1 | 1
Parker | 1 | 2
Stark | 1 | 1
Rogers | 1 | 1
Rogers | 1 | 2
Parker | 1 | 3
Given this data, how do I get all the unique Student name with the highest Attempt?
I'm attempting to get this result:
Learner | AssesmentId | Attempt
------------------------------------
Parker | 1 | 3
Stark | 1 | 1
Rogers | 1 | 2
How can I do this in a single query in LINQ?
from la in _context.LearnerAssessments
where la.AssessmentId == assessmentId
&& learnerIds.Contains(la.LearnerId)
&& la.Attempt == {highest attempt}
var data = from list in _context.LearnerAssessments
group list by new
{
list.Learner,
list.AssesmentId
}
into g
select new
{
g.Key.Learner,
g.Key.AssesmentId,
Max= g.Max(x=>x.Attempt)
};
or using fluent API :
var data = _context.LearnerAssessments.GroupBy(l => new { l.Learner, l.AssesmentId }, (keys, item) => new
{
Key = keys,
MaxAttemp = item.Max(x => x.Attempt)
}).Select(x => new LearnerAssessment
{
Learner = x.Key.Learner,
Attempt = x.MaxAttemp,
AssesmentId = x.Key.AssesmentId
});
How can I get relationship records across multiple fields
Following the example below, I want to return a category with id 2 only if all the conditions are met, namely option [1, 5, 8] with active = 1
Please help me, I searched through a lot of information and did not find a solution
`$options = [1, 5, 8];
$categories = Category::whereHas('products', function ($query) use ($options){
$query->where(....);
})->get();`
`
```
My Model Category
```
`class Category extends Model
{
public function products()
{
return $this->hasMany(Product::class, "category_id");
}
}`
```
Table products
| id | category_id | active | option |
| -------- | ----------- | ------ | ------ |
| 1 | 2 | 1 | 1 |
| 2 | 13 | 1 | 2 |
| 3 | 28 | 0 | 3 |
| 4 | 2 | 1 | 5 |
| 5 | 2 | 1 | 8 |
```
$options = [1, 5, 8];
$categories = Category::whereHas('products', function ($query) use ($options){
$query->whereIn('option',$options)->where('active',1);
})->get();
Suppose that you have a list of formulas like the following one:
KPI1 = somevalue1 + somevalue2
KPI2 = somevalue1 + somevalue3
KPI3 = KPI1 + somevalue4
KPI4 = KPI2 + KPI3
etc.
Which is the optimal algorithm that can be used to obtain a relationship tree for each of the elements referenced in the formulas?
i.e., using the example above:
+------------------------------------------------------------+
| somevalue3 somevalue1 somevalue2 somevalue4 |
| | | | | | |
| --------------- -------------- | |
| | | | |
| KPI2 KPI1 | |
| | | | |
| | --------------------- |
| | | |
| | KPI3 |
| | | |
| --------------------------- |
| | |
| KPI4 |
+------------------------------------------------------------+
You can use a hashmap where a key corresponds to a defined name (e.g. "KPI3"), and the corresponding value is a list of names/values on which that name depends (e.g. ["KPI1", somevalue4]).
Here is an implementation in JavaScript, where we can use the native Map constructor. Once the map is populated with all the dependencies, a recursive function can for example print the tree:
function printTree(map, name, indent="") {
console.log(indent + name);
let children = map.get(name);
if (children !== undefined) {
for (let childName of children) {
printTree(map, childName, indent+" ");
}
}
}
let map = new Map();
map.set("KPI1", ["value1", "value2"]);
map.set("KPI2", ["value1", "value3"]);
map.set("KPI3", ["KPI1", "value4"]);
map.set("KPI4", ["KPI2", "KPI3"]);
printTree(map, "KPI4");
In Python you would use a dictionary:
def print_tree(d, name, indent=""):
print(indent + name)
children = d.get(name, None)
if children is not None:
for childName in children:
print_tree(d, childName, indent+" ")
d = dict()
d["KPI1"] = ["value1", "value2"]
d["KPI2"] = ["value1", "value3"]
d["KPI3"] = ["KPI1", "value4"]
d["KPI4"] = ["KPI2", "KPI3"]
print_tree(d, "KPI4")
I have a question table which has a type_id column. The value defined here relates to the QuestionTypes model.
Question Table:
--------------------------
| id | title | type_id |
--------------------------
| 1 | apple? | 2 |
| 3 | banana? | 2 |
| 4 | kiwi? | 2 |
| 5 | pear? | 3 |
--------------------------
QuestionTypes
----------------
| id | title |
----------------
| 1 | multi |
| 2 | single |
| 3 | free |
----------------
In the Questions Model I have:
public function type()
{
return $this->hasOne(QuestionType::class);
}
I would like to print the title from questiontypes table but when I try to output in the view using $question->type->title I get:
Column not found: 1054 Unknown column 'x__questiontypes.questions_id' in 'where clause'
(SQL: select * from `x__questiontypes` where `x__questiontypes`.`questions_id` = 2 and `x__questiontypes`.`questions_id` is not null limit 1
Have I mixed up the relationships?
Solution via Attaching a hasOne model to another Laravel/Eloquent model without specifying id
Updated to Questions model:
public function type()
{
return $this->belongsTo(QuestionType::class, 'type_id');
}
Added to QuestionType model:
public function questions()
{
return $this->hasMany(Question::class, 'type_id');
}
Book
----------------------------
| id | name | published |
----------------------------
| 1 | book1 | 1 |
| 2 | book2 | 1 |
| 3 | book3 | 0 |
Chapter
----------------------------
| id | book_id | name | published |
----------------------------
| 1 | 1 | chapter1 | 1 |
| 2 | 1 | chapter2 | 0 |
| 2 | 2 | chapter1 | 0 |
| 3 | 3 | chapter1 | 1 |
class Book{
public function getChapter()
{
return $this->hasMany(Chapter::className(), ['kook_id' => 'id']);
} }
class Chapter{
public function getBook()
{
return $this->hasOne(Book::className(), ['id' => 'book_id']);
} }
How can i get published books with published pages using ActiveRecord (i want get book1 with chapter1 and book2 without any chapters)?
smth like Book::find($id)->where(['published' => 1])-> {{{left join with where}}} ->all())
ADDED
And then i wand to use it
echo $book->name;
foreach($book->getChapter() as chapter){
echo chapter->name;
}
Change your Book class relation as
class Book
{
public function getChapter()
{
return $this->hasMany(Chapter::className(), ['book_id' => 'id'])->where(['published' => 1]);
}
}
To get Related Records use with()
Book::find()->with(['chapter'])->where(['id' => $id ,'published' => 1])->all()
To Use it:
//Book Name
echo $book->name;
//For Chapters Name
if($book->chapter){
foreach($book->chapter as $chapter){
echo $chapter->name;
}
}