Athari / YaLinqo

Yet Another LINQ to Objects for PHP [Simplified BSD]
https://athari.github.io/YaLinqo
BSD 2-Clause "Simplified" License
439 stars 39 forks source link

Two conditions within where clause #48

Closed wpplumber closed 2 years ago

wpplumber commented 4 years ago

While I'm trying to iterate through the WP users table to check meta option where ID and meta_key are the where clause conditions used in the following code:

$db_usermeta = $wpdb->get_results('SELECT * FROM ' . $wpdb->usermeta );
foreach ($db_users as $key => $row) {
      $usermeta = from($db_usermeta)
      ->where(function($db_usermeta) {
      return $db_usermeta["user_id"] === $row->ID && 
      $db_usermeta["meta_key"] === "co_dateofbirth" ;})
      ->toString();
     echo 'co_dateofbirth value is : ' . $usermeta . '<br/>';
}
Athari commented 4 years ago

The where method returns a sequence of elements. If you need only one element, you should use first (if you're absolutely sure at least one element exists) or firstOrDefault (it returns default null if the searched sequence is empty). It also returns the whole row, not just the value, so you need to get meta_value. So your code becomes:

$usermetas = $wpdb->get_results("SELECT * FROM {$wpdb->usermeta}");
foreach ($users as $user) {
    $dateOfBirth = from($usermetas)
        ->firstOrDefault(function($um) {
            return $um['user_id'] === $user->ID && $um['meta_key'] === 'co_dateofbirth' ;});
    if ($dateOfBirth != null)
        echo "co_dateofbirth value is: {$dateOfBirth->meta_value}<br/>";
}

Or, if all users are guaranteed to have a date of birth:

$usermetas = $wpdb->get_results("SELECT * FROM {$wpdb->usermeta}");
foreach ($users as $user) {
    $dateOfBirth = from($usermetas)
        ->first(function($um) {
            return $um['user_id'] === $user->ID && $um['meta_key'] === 'co_dateofbirth' ;});
    echo "co_dateofbirth value is: {$dateOfBirth->meta_value}<br/>";
}

Note that your code is inefficient because it puts the whole UserMeta table into memory while you only need dates of birth. It would be more optimal modify your SQL query to get all your data at once and only it.

The following query would return only the data you actually need:

SELECT u.id, um.meta_value
FROM user AS u
  INNER JOIN usermeta AS um ON um.user_id = u.id
WHERE um.meta_key = 'co_dateofbirth'

In general, if a query is possible within SQL, you should perform it within SQL. You should only use YaLinqo (and any filtering and transformation using array functions in general) only in cases SQL is unavailable.

(I haven't tested any of the code above.)

wpplumber commented 4 years ago

The code seems returning wrong field which is the 1st on table, is it a problem on the first function conditions! image