鍍金池/ 問答/PHP/ 控制器里面怎樣使用eloquent的數(shù)據(jù)?

控制器里面怎樣使用eloquent的數(shù)據(jù)?

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class User extends Model
{
     protected $table = 'user';
     protected $primaryKey = 'id';
     public $timestamps = false;
     public function comment(){
         return $this->hasMany('App\Models\Comment', 'uid', 'uid');
     }
}

比如eloquent里面上面這樣寫的 我控制器中這樣使用為什么不對?

use App\Models\User;
class TestController extends Controller{
     public function test(){
       $a=new User();
       var_dump($a->comment());
  }
}
回答
編輯回答
喵小咪

注意用法, 參考 https://laravel.com/docs/5.6/...

但推薦都換成復數(shù)的, 符合語義, 許多評論嘛,

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class User extends Model
{
     protected $table = 'user';
     protected $primaryKey = 'id';
     public $timestamps = false;
     public function comments(){ // 注意這里, 用屬性
         return $this->hasMany('App\Models\Comment', 'uid', 'uid');
     }
}
use App\Models\User;
class TestController extends Controller{
     public function test(){
       $user = User::first();   // 注意這里, 取一個用戶
       // 當然, 這個用戶沒數(shù)據(jù), 試著換一個用戶, 比如
       // $user = User::find(100); // 取 id 為 100 的用戶, 看他有沒有評論數(shù)據(jù),
       var_dump($user->comments); // 注意這里, 用屬性
  }
}
2017年12月25日 18:21