Can you display your model here because you have to add in model as like below.
protected $primaryKey = 'id';
I have a test model and a question model, with a many to many relationship. I am making a method that combines n tests. It takes all the questions in all the tests and creates a new test using the questions on the tests, removing duplicates.
$questions = $questions->unique('id')->sortBy('id');
But I can not simply use the ID. See, each question has a tag field, which I am using for localization purposes (@lang(questions.the_tag_here)). This field is unique for almost every question. But, there are some questions that share the exact same text, so they are using the exact same tag. The text may be the same, but for there are key differences in other fields. There can not be more than one of these questions in the same test, so in the event of combining two or more tests, if these questions are present, I need to take only the one with the longest string in one of the other fields.
If I simply do this:
$questions = $questions->unique('tag')->sortBy('id');
It will choose to keep the first question on the database.
How can I choose the one with the longest string on that other field instead?
Edit:
Using Laravel's documentation as example:
$collection = collect([
['name' => 'iPhone 6', 'brand' => 'Apple', 'type' => 'phone'],
['name' => 'iPhone 5', 'brand' => 'Apple', 'type' => 'phone'],
['name' => 'Apple Watch', 'brand' => 'Apple', 'type' => 'watch'],
['name' => 'Galaxy S6', 'brand' => 'Samsung', 'type' => 'phone'],
['name' => 'Galaxy Gear', 'brand' => 'Samsung', 'type' => 'watch'],
]);
$unique = $collection->unique('brand');
$unique->values()->all();
/*
[
['name' => 'iPhone 6', 'brand' => 'Apple', 'type' => 'phone'],
['name' => 'Galaxy S6', 'brand' => 'Samsung', 'type' => 'phone'],
]
*/
What if I want the iPhone 5 instead of the 6?
P.D: I hope I explained myself well, english is not my first language.
i guess first you need make sorting
$questions = $questions->sortByDesc(function ($item) {
return strlen($item->YOUR PROPERTY);
});
and then
$questions = $questions->unique('tag')
or shorter
$questions = $questions->sortByDesc(function ($item) {
return strlen($item->YOUR PROPERTY);
})->unique('tag');
Please or to participate in this conversation.