从数据库中获取有条件的数据并在视图中显示 [英] Get data from database with condition and show it in a view

查看:64
本文介绍了从数据库中获取有条件的数据并在视图中显示的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我在数据库中拥有的数据

这就是我想在view.blade.php中创建的内容

我想做的是我想从数据库中获取数据,如果列中的数据是1,我想获取列名,如您在图2中看到的那样,但是可能超过1个列名称,因为包含数据的列可以是A,B,C ...等列.如果其中的数据是视图中为1'.我坚持如何获得所有这些主题A,B,C ..这是我编写的代码,但是它不完整,因为我不知道要像上面提到的那样添加什么.希望有人可以帮助我.预先感谢

What I want to do is I want to get the data from the database, if the data inside the column is 1, I want to get the column name as you can see in image 2, but there could be more than 1 column name because the column with data can be column A,B,C... etc.. and I want to show the student name and the subject (a,b,c... etc) if the data in it is '1' in the view. I stuck on how to get all those subject A,B,C.. this is the code that I have written, but it is incomplete because I don't know what to add on it to make it as what I have mentioned above. Hopefully, someone can help me. Thanks in advance

if($row->'A'=='1'){i dont know what should i put here so that i cant get the column name 'A' and print it in view.blade.php}

推荐答案

假定数据库中的表为student_details,请在app/models/StudentDetail.php内创建一个雄辩的模型StudentDetail:

Assuming your table in database is student_details, create an eloquent model StudentDetail inside app/models/StudentDetail.php :

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class StudentDetail extends Model
{
    /**
     * The table associated with the model.
     *
     * @var string
     */
    protected $table = 'student_details';

    /**
     * Get subjects in the view
     * 
     * @return string
     */
    public function getSubjects()
    {
        $subjects = [];
        $subjects[] = $this->A == 1 ? 'A' : null;
        $subjects[] = $this->B == 1 ? 'B' : null;
        $subjects[] = $this->C == 1 ? 'C' : null;
        $subjects = array_filter($subjects);

        return implode(',', $subjects);
    }

}

然后您可以在控制器中检索数据:

Then you can retrieve data in your controller :

public function view()
{
    $studentDetails = StudentDetail::get();

    return view('view.path', compact('studentDetails'));
}

在内部视图中,您可以执行以下操作:

And inside view you can do :

@foreach($studentDetails as $detail)

    {{ $detail->name }} : {{ $detail->getSubjects() }}
@endforeach

您也可以使用附加属性,因为在实例化模型时每次都会添加附加属性,所以我没有用过.我相信将其包含在函数中可以使其在需要时灵活使用.

You can use appended property as well, I have not used that because appended property is added every-time when model is instantiated. I believe having it in a function makes it flexible to use as and when needed.

这篇关于从数据库中获取有条件的数据并在视图中显示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆