当前位置: 首页 > 知识库问答 >
问题:

SQLSTATE[42S22]:未找到列:1054未知列'clientes.clientes_id'

湛功
2023-03-14

我是编程界的新手,我自己在学习laravel,我发现了这个错误:SQLSTATE[42S22]:Column not found:1054未知列'clientes.clientes\u id'在'where子句中(SQL:select*fromclienteswhereclientsclients\u id=1和clientsclients\u id不为空)(视图:/shared/httpd/laravel_8_crud/resources/views/pedidos/index.blade.php)

有人能帮我处理这个案子吗?

我的目标是显示数据库中记录的具有此关系的客户名称。

提前谢谢。

移民:

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreatePedidosTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('pedidos', function (Blueprint $table) {
            $table->id();
            $table->enum('status',['aberto', 'pago', 'cancelado',]);
            $table->bigInteger('clientes_id')->unsigned();
            $table->foreign('clientes_id')->references('id')->on('clientes')->onCascade('delete');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('pedidos');
    }
}

型号:

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Pedido extends Model
{

    protected $table = 'pedidos';
    public $timestamps = true;

    protected $fillable = [
        'status',
        'clientes_id',
        'created_at'
    ];

    public function clientes()
    {
        return $this->hasMany(Cliente::class, 'clientes_id', 'id');
    }
}

控制器

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Pedido;
use App\Models\Cliente;

class PedidosController extends Controller
{
    /**
     * mostrar conteudo no index
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $pedidos = Pedido::orderBy('id','asc')->paginate(10);

        return view('pedidos.index', compact('pedidos'))
            ->with('i', (request()->input('page', 1) - 1) * 5);
    }

    /**
     * Mostra o form para criar um novo pedido.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        $clientes = Cliente::all();
        return view('pedidos.create', compact('clientes'));
    }

    /**
     * armazena um novo pedido pra enviar ao BD
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $request->validate([
            'status' => 'required',
            'clientes_id' => 'required'
        ]);

        Pedido::create($request->all());

        return redirect()->route('pedidos.index')
            ->with('success', 'Pedido cadastrado com sucesso');
    }

    /**
     * Exibe um pedido
     *
     * @param  \App\Models\Pedido  $pedido
     * @return \Illuminate\Http\Response
     */
    public function show(Pedido $pedido)
    {
        return view('pedidos.show', compact('pedido'));
    }

    /**
     * Exibe um pedido para edição
     *
     * @param  \App\Models\Pedido  $pedido
     * @return \Illuminate\Http\Response
     */
    public function edit(Pedido $pedido)
    {
        return view('pedidos.edit', compact('pedido'));
    }
    /**
     * Atualiza um pedido no BD
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\Models\Pedido  $pedido
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, Pedido $pedido)
    {
        $request->validate([
            'status' => 'required',
        ]);
        $pedido->update($request->all());

        return redirect()->route('pedidos.index')
            ->with('success', 'Pedido atualizado com sucesso');
    }
    /**
     * Remove um pedido do BD
     *
     * @param  \App\Models\Pedido  $pedido
     * @return \Illuminate\Http\Response
     */
    public function destroy(Pedido $pedido)
    {
        $pedido->delete();

        return redirect()->route('pedidos.index')
            ->with('success', 'Pedido deletado com sucesso');
    }
}

索引

@extends('layouts.app')
@section('content')
</br>
<div class="container content">
    <div class="row">
        <div class="col-md ">
            <div class="pull-left">
                <h2>Cadastro de Pedidos</h2>
            </div>
            </br>
            @if ($message = Session::get('success'))
            <div class="alert alert-success">
                <p>{{ $message }}</p>
            </div>
            @endif

            <table class="table table-hover">
                <thead>
                    <tr>
                        <th scope="col">Nº</th>
                        <th scope="col">Cliente</th>
                        <th scope="col">Status</th>
                        <th scope="col">Data de criação</th>
                        <th scope="col">Ação</th>
                    </tr>
                </thead>
                <tbody>
                    @foreach ($pedidos as $pedido)
                    <tr>
                        <td scope="row">{{ $pedido->id }}</td>
                        <td scope="row">{{ $pedido->clientes }}</td> //This line error if $pedido->cliente_id  bring me the ID, but I would like to display the name
                        <td scope="row">{{ $pedido->status }}</td>
                        <td scope="row">{{ date_format($pedido->created_at, 'd-m-Y H:i:s') }}</td>
                        <td>
                            <form action="{{ route('pedidos.destroy', $pedido->id) }}" method="POST">
                                <a href="{{ route('pedidos.show', $pedido->id) }}" title="Visualizar">
                                    <i class="fas fa-eye text-success fa-lg"></i>
                                </a>
                                <a href="{{ route('pedidos.edit', $pedido->id) }}" title="Editar">
                                    <i class="fas fa-edit fa-lg"></i>
                                </a>
                                @csrf
                                @method('DELETE')
                                <button type="submit" title="Deletar" style="border: none; background-color:transparent;">
                                    <i class="fas fa-trash fa-lg text-danger"></i>
                                </button>
                            </form>
                        </td>
                    </tr>
                    @endforeach
                </tbody>
            </table>
            <div class="pull-right">
                <a class="btn btn-success" href="{{ route('pedidos.create') }}" title="Adicionar um Pedido"> <i class="fas fa-plus-circle"></i>
                </a>
            </div>
        </div>
    </div>
</div>

{!! $pedidos->links() !!}

@endsection

共有1个答案

亢正德
2023-03-14

因为clinetes_id是pedido中的外键,所以在这个模型中需要定义一个属于关系。所以pedido是属于客户的

<?php
    
    namespace App\Models;
    
    use Illuminate\Database\Eloquent\Model;
    
    class Pedido extends Model
    {
    
        protected $table = 'pedidos';
        public $timestamps = true;
    
        protected $fillable = [
            'status',
            'clientes_id',
            'created_at'
        ];
    
        public function clientes()
        {
            return $this->belongsTo(Cliente::class, 'clientes_id');
        }
    }

index.php

@extends('layouts.app')
@section('content')
</br>
<div class="container content">
    <div class="row">
        <div class="col-md ">
            <div class="pull-left">
                <h2>Cadastro de Pedidos</h2>
            </div>
            </br>
            @if ($message = Session::get('success'))
            <div class="alert alert-success">
                <p>{{ $message }}</p>
            </div>
            @endif

            <table class="table table-hover">
                <thead>
                    <tr>
                        <th scope="col">Nº</th>
                        <th scope="col">Cliente</th>
                        <th scope="col">Status</th>
                        <th scope="col">Data de criação</th>
                        <th scope="col">Ação</th>
                    </tr>
                </thead>
                <tbody>
                    @foreach ($pedidos as $pedido)
                    <tr>
                        <td scope="row">{{ $pedido->id }}</td>
                        <td scope="row">{{ $pedido->clientes->name }}</td> 
                        <td scope="row">{{ $pedido->status }}</td>
                        <td scope="row">{{ date_format($pedido->created_at, 'd-m-Y H:i:s') }}</td>
                        <td>
                            <form action="{{ route('pedidos.destroy', $pedido->id) }}" method="POST">
                                <a href="{{ route('pedidos.show', $pedido->id) }}" title="Visualizar">
                                    <i class="fas fa-eye text-success fa-lg"></i>
                                </a>
                                <a href="{{ route('pedidos.edit', $pedido->id) }}" title="Editar">
                                    <i class="fas fa-edit fa-lg"></i>
                                </a>
                                @csrf
                                @method('DELETE')
                                <button type="submit" title="Deletar" style="border: none; background-color:transparent;">
                                    <i class="fas fa-trash fa-lg text-danger"></i>
                                </button>
                            </form>
                        </td>
                    </tr>
                    @endforeach
                </tbody>
            </table>
            <div class="pull-right">
                <a class="btn btn-success" href="{{ route('pedidos.create') }}" title="Adicionar um Pedido"> <i class="fas fa-plus-circle"></i>
                </a>
            </div>
        </div>
    </div>
</div>

{!! $pedidos->links() !!}

@endsection
 类似资料:
  • 我使用的框架Laravel。 我有两个表(用户和成员)。当我想登录时,我会收到错误消息: SQLSTATE[42S22]:找不到列: 1054未知的列'user_email'in'where子句'(SQL:选择*fromwhere=?限制1)(绑定:数组(0= 表用户 表成员 迁移用户 移民成员 模型用户 模范会员 成员模型使用:使用照明\Auth\UserInterface; 控制器 auth.

  • 我正在尝试使用PDO向MySQL插入一条记录,下面的代码中可以看到我的sql语句。 当执行此代码时,我会遇到以下错误消息; SQLState[42S22]:找不到列:1054“Field List”中的未知列“John” 这无疑是解决这个问题的一个简单方法,但我似乎看不出来,有人能给我指明正确的方向吗?

  • 问题内容: 我正在使用Laravel框架。 我有2个表(用户和成员)。当我想登录时,收到错误消息: SQLSTATE [42S22]:找不到列:1054’where子句’中的未知列’user_email’(SQL:select * from where =?limit 1)(绑定:数组(0 =>'test@hotmail.com‘,)) 表用户 表成员 迁移用户 移民会员 模型使用者 模范会员 成

  • 我的代码:数据库中的值未更新,出现以下错误: (照明\数据库\查询异常(42S22)SQLSTATE[42S22]:找不到列: 1054未知列'用户名'在'where子句'(SQL:选择计数()作为聚合从其中=anikatabassum))和("SQLSTATE[42S22]:找不到列: 1054未知列'用户名'在'where子句'(SQL:选择计数()作为聚合从其中=anikatabassum)

  • 我正在制作一个我想登录和注册的应用程序,并且能够将csv文件导入数据库,注册和登录工作正常,但是当我想导入csv时,我遇到了这个问题: 错误luminate\Database\QueryException SQLSTATE[42S22]:未找到列:1054“where子句”中的未知列“classe”(SQL:select*fromwhere(=7和=7598)限制1)科目表 账户控制员

  • 我有查询异常SQLSTATE[42S22]:列未找到: 1054 Champ'3'在子句(SQL:选择,,从内连接