【问题标题】:Eloquent relationship in LaravelLaravel 中雄辩的关系
【发布时间】:2016-07-20 23:54:20
【问题描述】:

我有以下表格结构:

Table Name - Users
    Column: id, name, email, etc

Table Name - Plugins
    Column: id, theme_id, type_id, code,

Table Name - Templates
    Column: id, theme_id, user_id, templatedata

Table Name - Userplugins
    Column: id, user_id, plugins_id, contents

现在我正在调用 ID 为 templates 的路由,其中​​ templatedata 具有 JSON 数据,我可以通过以下代码在刀片文件中获取 Plugins code

@foreach($gettemplate as $renderer)

    {!! $plugins->find($renderer)->code !!}

@endforeach

但我无法获取UserPlugins 表中的内容。以下是我正在尝试这样做的controller

public function get_template($id)
{
    $template = Template::findOrFail($id);
    $gettemplate = json_decode($template->templatedata);
    $plugins = Plugins::all();
    $user = User::findorFail($id);
    return $user->userplugins()->contents;
    //return view('nitseditor.test', ['plugins' => $plugins, 'gettemplate' => $gettemplate, 'user' => $user]);
}

我已经注释掉了我的观点只是为了检查输出。 我在model 中定义了relationship 我的App/User.php 文件包含:

public function userplugins(){

    return $this->hasMany('App\UserPlugin');
}

App\UserPlugin.php 文件中我有:

protected $fillable = [

    'contents',

];

我收到以下错误:

未定义属性:Illuminate\Database\Eloquent\Relations\HasMany::$contents

请帮帮我,谢谢。

【问题讨论】:

    标签: laravel eloquent laravel-5.2


    【解决方案1】:

    在下面一行:

    return $user->userplugins()->contents;
    

    当您调用$user->userplugins() 时,这意味着您调用了关系方法。它不会为您返回 Eloquent Collection 或 Eloquent Object。

    你需要打电话

    $user->userplugins
    

    获取UserPlugin的集合

    但是,当你调用

    return $user->userplugins->contents;
    

    你会得到错误,因为return $user->userplugins是一个Eloquent Collection,你不能从中获取内容。

    您可以获取特定 UserPlugin 的内容。比如user的第一个UserPlugin like:

    return $user->userplugins()->first()->contents;
    

    【讨论】:

      猜你喜欢
      • 2018-11-12
      • 2015-03-14
      • 2018-11-28
      • 2015-01-11
      • 2021-06-03
      • 2020-03-26
      • 1970-01-01
      相关资源
      最近更新 更多