Laravel Model子类模型的绑定

时间:2018-05-17 12:42:24

标签: php laravel dependency-injection laravel-5.5

我在路由模型绑定我的Eloquent子类时遇到了一些麻烦。以下代码工作正常:

$repo = new \App\Repositories\Eloquent\PluginRepository();
$plugin = $repo->findOrFail(1);
var_dump($plugin->type);

输出

object(App\PluginsTypes)#360 (26) {...}

但是当我制作模型绑定时,就像这样:

路由/ web.php

Route::resource('plugins', 'PluginsController');

应用/ HTTP /控制器/管理/ PluginsController.php

public function edit(PluginRepositoryInterface $plugin){
    var_dump($plugin); // object(App\Repositories\Eloquent\PluginRepository)#345 (26) {...}
    var_dump($plugin->id); // NULL
}

所以问题是,它没有找到路径中传递的id。

Laravel项目中的添加代码:

应用/ Plugins.php

<?php

namespace App;

class Plugins extends Model{
    // My Eloquent Model

    /**
     * The foreignKey and ownerKey needs to be set, for the relation to work in subclass.
     */
    public function type(){
        return $this->belongsTo(PluginsTypes::class, 'plugin_type_id', 'id');
    }
}

应用/库/ SomeRepository.php

<?php

namespace App\Repositories;

use App\Abilities\HasParentModel;

class PluginsRepository extends Plugins{
    protected $table = 'some_table';

    use HasParentModel;
}

配置/ app.php

'providers' => [
    ...
    App\Repositories\Providers\PluginRepositoryServiceProvider::class,
    ...
]

应用/库/提供者/ PluginRepositoryServiceProvider.php

<?php

namespace App\Repositories\Providers;

use Illuminate\Support\ServiceProvider;

class PluginRepositoryServiceProvider extends ServiceProvider{

    /**
     * This registers the plugin repository - added in app/config/app.php
     */
    public function register(){
        // To change the data source, replace the concrete class name with another implementation
        $this->app->bind(
            'App\Repositories\Contracts\PluginRepositoryInterface',
            'App\Repositories\Eloquent\PluginRepository'
        );
    }
}

使用这些资源:

HasParentModel Trait on GitHub

Extending Models in Eloquent

1 个答案:

答案 0 :(得分:0)

我在文档中找到了答案(当然):

自定义分辨率逻辑

部分中的

https://laravel.com/docs/5.6/routing#route-model-binding

在我的 app / Repositories / Providers / PluginRepositoryServiceProvider.php 中,我在界面绑定下添加了以下内容,现在可以正常使用。

$this->app->router->bind('plugin', function ($value) {
        return \App\Repositories\Eloquent\PluginRepository::where('id', $value)->first() ?? abort(404);
});

我可能会重命名它,但它就像一个魅力:)好日子......

相关问题