【问题标题】:How to get reference table data in Laravel 5.1如何在 Laravel 5.1 中获取参考表数据
【发布时间】:2016-01-31 14:07:59
【问题描述】:

我用accountgroup_id 创建了一个模型Account,它引用自Account_group 模型。然后我像这样从route 调用它

 Route::get('test', function () {
    return \App\Account::get()->account_group;
  });

Account 模型与 Account_group

belogsto 关系
 class Account extends Model
 {
     protected $fillable = ['accountgroup_id', 'accountno', 'accountname','address','contactno'];

   public function account_group()
   {
         return $this->belongsTo('App\Account_group');
   }
 }

Account_group 模型与 Account 具有 hasMany 关系

class Account_group extends Model
{
   protected $fillable =['name','under'];
   public function account()
   {
    return $this->hasMany('App\Account','accountgroup_id');
   }
 }

但是在调用路由之后;我收到以下错误。

未定义的属性: Illuminate\Database\Eloquent\Collection::$account_group

【问题讨论】:

    标签: php laravel-5.1


    【解决方案1】:

    通过使用帐户组调用帐户解决了我的问题

       \App\Account::with('account_group')->get();
    

    【讨论】:

      【解决方案2】:

      首先,第二个类应该命名为AccountGroup

      仔细阅读错误将为您提供关于发生了什么的线索 - \App\Account::get() 返回一个由Account 对象组成的集合,每个对象都有一个AccountGroup。所以你需要选择你想要的具体Account,然后你就可以访问它上面的account_group属性:

      \App\Account::find(1)->account_group; // get Account with ID 1
      \App\Account::first()->account_group; // get the first Account record
      

      【讨论】:

        猜你喜欢
        • 2016-02-02
        • 1970-01-01
        • 2022-07-01
        • 1970-01-01
        • 2020-08-11
        • 2015-11-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多