【问题标题】:Why does only some laravel routes return model attributes?为什么只有一些 laravel 路由返回模型属性?
【发布时间】:2020-08-07 11:47:47
【问题描述】:

我正在学习 laravel 但有一些疑问..

控制器

namespace App\Http\Controllers;

use App\ItemNfe;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class ItensNfeController extends Controller
{
public function edit($id,ItemNfe $itemNfe)
    {
        //i don´t want to have to make this select below
        //$itemNfe = DB::table('itens_nfe')->where('id_itemnfe',$id)->get();

        // dd($itemNfe); this dd() returns model attributes on few of my controllers only
        return view...
    }...

模型:(注意我没有使用 laravel 约定,但它是知情的)

namespace App;

use Illuminate\Database\Eloquent\Model;

class ItemNfe extends Model
{
    protected $table = 'itens_nfe';

    protected $primaryKey = 'id_itemnfe';

    protected $fillable = [
        'id_itemnfe','fk_venda', 'fk_produto'...
    ];

    public function nfe()
    {
        return $this->belongsTo('App\Nfe'); //this is one diference among others models, but apparently doesn´t affects when i tested without this code.
    }
}

我使用的路线对每个人都是一样的......“资源路线” 在前 2 个,我有返回的属性,但不是在最后一个......

    Route::resource('/usuarios', 'UsuariosController');
    Route::resource('/nfes', 'NfesController');
    Route::resource('/itensnfe', 'ItensNfeController');

使用的网址是: https://localhost/erpoverweb/public/itensnfe/1/edit

如果需要更多代码,请告诉我...谢谢!

【问题讨论】:

    标签: php laravel orm model


    【解决方案1】:

    如果您不想手动搜索数据库中的条目,可以使用 Laravel Container 执行依赖注入。 https://laravel.com/docs/7.x/container#introduction

    public function edit(ItemNfe $itemNfe)
    {
        // Returns the model, and you didn't need to manually searched.
        // Laravel automaticly injects this for you.
        dd($itemNfe);
    }
    

    【讨论】:

    • 我以前做过,但它部分工作......只有在那个控制器上我收到一个空的属性数组......我不知道为什么。
    • 您必须将路由参数与控制器参数匹配。 Route::get('/item/{item}') public function getItem(Item $item) { }
    【解决方案2】:

    听起来您正在寻找 Route Model Binding(隐含)。这要求路由参数名称和该路由的方法签名的参数名称匹配。

    public function edit(ItemNfe $itensnfe)
    

    资源名称为“itensnfe”的资源路由应将参数设为“itensnfe”。

    如果你不进行这些匹配,你最终会得到依赖注入,它会注入一个新的模型实例。

    Laravel 7.x Docs - Routing - Route Model Binding - Implicit Binding

    【讨论】:

      猜你喜欢
      • 2019-05-12
      • 2014-09-30
      • 2021-01-25
      • 2015-06-24
      • 2018-02-07
      • 1970-01-01
      • 2019-11-15
      • 1970-01-01
      • 2011-02-14
      相关资源
      最近更新 更多