Reputation: 2963
I have this query:
$subcommon= MyModel::selectRaw('subjectlist_id, count(subjectlist_id) AS aggregate')
->whereIn('user_id', [Auth::id(), $user->id])
->groupBy('subjectlist_id')
->having('aggregate','>',1)
->get();
which gives this query result:
{"subjectlist_id":1,"aggregate":2} {"subjectlist_id":3,"aggregate":2}
I also have this query:
$values = Mysecondmodel::where('user_id', Auth::id())
->first();
which gives this result:
{"id":1,"subjectlist_id":1, "article_id":4}
Because im finding it way too difficult to join these two models i've decided to output them as arrays so I would like at least 1 matching value for subjectlist_id
as a condition for it to execute the query I've displayed at the bottom. I'm assuming it's the arrayintersect
method however im unsure how to use it.
$values = Mysecondmodel::where('user_id', Auth::id())
->first();
I have this so far:
$subcommonarray = (array) $subcommon;
$valuesarray = (array) $values;
$a = $subcommonarray;
$b = $valuesarray;
$c = array_intersect_key($a, $b);
if (count($c) > 0) {
$newquery = Mysecondmodel::where(user_id, Auth::id())
->first();
}
But this I think is comparing the keys and not the values. How do I match the values and and the key together?
Upvotes: 1
Views: 2990
Reputation: 2100
Well if $values
and $subcommon
are both valid arrays, you could compare them using the array_intersect
function like that:
$subjectlist_id = array_intersect($values, $subcommon);
This would go and search for similarities in values, and will construct another array in the $subjectlist_id
variable of all the matching values between both arrays.
A good example from the php documentation:
$array1 = array(2, 4, 6, 8, 10, 12);
$array2 = array(1, 2, 3, 4, 5, 6);
$array3 = array_intersect($array1, $array2);
var_dump($array3);
This would have such an array:
array(3) {
[0]=> int(2)
[1]=> int(4)
[2]=> int(6)
}
Upvotes: 2