【问题标题】:I want to refer to one of the database tables in one of the files in the views folder in my project我想在我的项目中的views文件夹中的一个文件中引用其中一个数据库表
【发布时间】:2019-06-30 21:38:50
【问题描述】:

我想在我的项目的views文件夹中的一个文件中引用其中一个数据库表 我怎样才能做到这一点? 例如: 显示名为 sub 的列的值,该列位于我的数据库的 configs 表中

请注意,我知道 html 不是服务器端语言;我只想显示我的信息,而不是编辑它

【问题讨论】:

  • 你的意思是要显示你的表的列名吗?
  • 不,我想显示该列的值
  • 你的问题不清楚!如果您想要一个列值,只需通过模型获取该表并回显列值,例如 $object = YourModel::find(1); 并将对象传递到您的视图并在那里打印。
  • 没有html代码?

标签: php html laravel


【解决方案1】:

如果你想使用MVC原理,你可以使用Eloquent Model来映射数据库信息,Controllers将模型数据发送到你的视图,Blade在你的视图中显示该数据。

只是一个基本的例子:

Config.phpApp 文件夹内的模型):

class Config extends Model
{
    /**
     * The table associated with the model, only needs to be defined 
     * if your table name isn't a plural of your model name
     *
     * @var string
     */
    protected $table = 'configs';
}

HomeControllerApp\Http\Controllers 中的控制器)

use App\Config;
...

class HomeController extends Controller
{
    public function index()
    {
        $configs = Config::all();

        return view('index', ['configs' => $configs]);
    }
}

index.blade.php(查看内部resources/views

@foreach ($configs as $config)
    {{ $config->sub }} // This prints the value of the sub column for every row in the configs table
@endforeach

【讨论】:

    【解决方案2】:

    好吧,您可以通过 DB 门面访问它。

    $column =  DB::table('configs')->pluck('sub');
    

    如果你有一个Config 模型,你可以这样得到它:

    $config = Config::find(1);
    $config->sub;
    

    您也可以在这里查看文档: https://laravel.com/docs/5.7/queries

    【讨论】:

      【解决方案3】:

      如果您想显示数据,您只需回显即可 对于单个元素这样做

      {{ $mode->colum_name }}
      

      如果你有多个元素,你可以这样制作

      @foreach($models as $model)
          {{$model->column_name}}
      @endforeach
      

      【讨论】:

        猜你喜欢
        • 2015-05-20
        • 2019-05-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-12-25
        • 1970-01-01
        • 1970-01-01
        • 2021-04-08
        相关资源
        最近更新 更多