Laravel如何使DB Raw罐头内部功能

时间:2018-09-24 03:38:58

标签: mysql sql laravel laravel-query-builder

我在laravel上有问题。我想雄辩地显示百分比,但返回空值

这是我的控制器

import React, { Component } from "react";
import Pagination from "../components/pagination";
import axios from 'axios';
class Posts extends Component {

  constructor(props) {
    super(props);
    this.state = {
      posts: [],
       page: 1,
      pages: 0,
      error: ""
    };
  }



  componentDidMount() {
  this.fetchPosts(this.state.page);
  }


async fetchPosts(page) {
  var self = this;
  try {
    const response = await axios.get('/posts', {
     headers: {
        Accept: "application/json",
        "Content-Type": "application/json",

      },
      data: { page: page },

//data: { page: this.state.page },
});

 if (response.status >= 200 && response.status < 300) {

         self.setState({ posts: response.data.posts, pages: parseInt(response.data.pages),
         page: parseInt(response.data.page) });

            } else {

                  self.setState({ error: response.data.error});

            }


  } catch (error) {
    console.error(error);
  }
}


    handleChangePage(page) {
    this.fetchPosts(page);
  }



  render() {
    var posts = this.state.posts.map(post => {
      return (
        <div key={post.id}>
          <h1>{post.id}</h1>
          <h1>{post.title}</h1>
          <p>{post.body}</p>
        </div>
      );
    });

    return (
      <div>


      {posts}

 <Pagination page={this.state.page}
                        pages={this.state.pages}
                        handleChangePage={this.handleChangePage} />
                        </div>

      );
  }
}

export default Posts;

这是Json的回报

  $group_categories = Proyek::with(['modul' => function($query){
        $query->select(DB::raw('((select count(*) from modul where status = 0 and deleted_at IS NULL) / 
                      (select count(*) from modul where deleted_at IS NULL)) * 
                        100 as count' ));
    }])->get();

1 个答案:

答案 0 :(得分:0)

您可以使用如下代码:

$all_models = (new Proyek)->count();
$models = (new Proyek)->where('status', 0)->count();
$percentage = $models / $all_models * 100;
$group_categories = Proyek::wheere('modul', $percentage);