按描述过滤JSON对象expressJS / UnderscoreJS

时间:2016-12-24 07:44:02

标签: javascript json node.js underscore.js

     public function like($pid)
     {
         $sql = "UPDATE postsinitial SET likes = likes+1 WHERE pid = ?";
         $this->_db->prepare($sql)->execute($_SESSION['user']);

         $sql = "INSERT IGNORE INTO userlikedposts (ulp_userid,ulp_postid) VALUES (?, ?)";
         $this->_db->prepare($sql)->execute([$_SESSION['user'], $pid]);

         $stmt = $this->_db->prepare("SELECT likes FROM postsinitial WHERE pid = ?");
         $stmt->execute([$pid]);
         return $stmt->fetchColumn();
     }

上面的示例阵列。

我想说只获得满足某个查询的对象。

  // make accessible your ORGANIZAZTION model with use eg: 
  // use common\models\ORGANIZATION;  or  
  use yourapp\models\ORGANIZATION;

  public function actionUpdate($id)
      {
          $model = $this->findModel($id);

          if (Yii::$app->request->post()) {
              try {
                  $state = true;
                  $data = Yii::$app->request->post();
                  $transaction = Yii::$app->db->beginTransaction();
                  $model->ID_APP = $data['USR']['ID_APP'];

                  // then  you can use eg: the  find method 
                  // related to ORGANIZAZTION active record   

                  $modelOrg =  ORGANIZATION::find()->where(['ID_APP']=> $data['USR']['ID_APP'])->one();
                  $model->NAMA_APP =  $modelOrg->NAMA_APP

                  ....

这是如何工作的?如何在underscore.where中输入函数作为谓词?

2 个答案:

答案 0 :(得分:0)

您可以在普通Javascript中使用Array#filter并使用正确的回调。



function byCompleted(item) {
    return item.completed;
}

function byId(id) {
    return function (item) {
        return item.id === id;
    };
}


var data = [{ id: 1, description: "Take out the trash", completed: false }, { id: 2, description: "Get food tonight", completed: false }, { id: 3, description: "Hit the gym", completed: true }];

console.log(data.filter(byCompleted));
console.log(data.filter(byId(2)));




答案 1 :(得分:0)

下划线where接受一个键:value对象作为其参数,而不是函数。如果你知道你想要哪些属性,这很方便。

示例:

var completed = _.where(todos,{completed:true});

var gymCompleted = _.where(todos,{completed:true,description:"Hit the gym"})

where返回包含指定属性的所有元素,findWhere返回第一个匹配元素。

如果您的过滤条件更复杂,并且您需要指定谓词,那么您必须使用filter,通过下划线或本机JS