How to get reference table data in Laravel 5.1


How to get reference table data in Laravel 5.1

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

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

帐户模型具有以下内容Account_group的关系

 class Account extends Model
 {
     protected $fillable = ['accountgroup_id', 'accountno', 'accountname','address','contactno'];
   public function account_group()
   {
         return $this->belongsTo('App'Account_group');
   }
 }

Account_group模型与账户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

首先,第二个类应该命名为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

我的问题通过调用账户组的账户解决

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