在使用 laravel 7 获得最高票数的候选人和他的名字时遇到问题

我正试图从得票最高的候选人那里得到他的名字,所有这些都试过失败。在获得所有总统候选人之后,我只是在下面添加()。


Illuminate\Database\Eloquent\Collection {#288 ▼

  #items: array:4 [▼

    0 => App\Candidate {#289 ▼

      #connection: "mysql"

      #table: "candidates"

      #primaryKey: "id"

      #keyType: "int"

      #attributes: array:9 [▼

        "id" => 1

        "name" => "Brian"

        "seat" => "president"

        "regno" => "DIT-C004-0536\2013"

        "votes" => 0     // this is the first candidate record, others are below.

        "user_id" => 2

        "created_at" => "2017-05-12 08:43:58"

        "updated_at" => "2017-05-12 08:43:58"

        "image" => ""

      ]


    }


    1 => App\Candidate {#290 ▼

      #attributes: array:9 [▼

        "id" => 5

        "name" => "Juma"

        "seat" => "president"

        "regno" => "DIT-C004-0516\2013"

        "votes" => 3

        "user_id" => 7

        "created_at" => "2017-05-12 09:03:03"

        "updated_at" => "2017-05-12 14:48:54"

        "image" => ""

      ]

    }


    2 => App\Candidate {#291 ▼

      #attributes: array:9 [▼

        "id" => 9

        "name" => "Stephen"

        "seat" => "president"

        "regno" => "0001"

        "votes" => 4           //trying to get the highest votes with the name.

        "user_id" => 12

        "created_at" => "2020-03-17 15:27:47"

        "updated_at" => "2020-03-21 19:18:39"

        "image" => ""

      ]

    }

    3 => App\Candidate {#292 ▼

      #attributes: array:9 [▼

        "id" => 10

        "name" => "Gobby"

        "seat" => "president"

        "regno" => "DIT-C004-0436\2014"

        "votes" => 0

        "user_id" => 11

        "created_at" => "2020-03-17 15:27:59"

        "updated_at" => "2020-03-17 15:27:59"

        "image" => ""

      ]

     }


我一直在四处寻找解决方案,但找不到,在此先感谢。



我在循环之前转储了代码,因为当我循环时它一直给我 0 或者有时告诉我数组不能转换为 int 之类的东西。


慕的地8271018
浏览 146回答 1
1回答

一只甜甜圈

在这种情况下,您的控制器代码应该是这样的:$seat = 'president';$name= 'gobby';$data = Candidate::where('seat', $seat)                  ->where('name', $name)                  ->orderBy('votes','desc')                  ->first()print_r($data);它将为您提供席位为“总统”和名称为“虾虎鱼”的最大选票数据
打开App,查看更多内容
随时随地看视频慕课网APP