2016-10-02 54 views
0

我不是一個專業程序員,所以我不知道我描述得很好。Laravel模型:實例還是關係?

雄辯關係建立在模型中,使用的語法和功能,如... - >belongsTo..

這些模型的背後,都在我的數據庫表。

在我的(laravel)應用程序中,我有一個登錄用戶需要有關其他用戶的某些信息。在一天結束時,他們都只是用戶,堅持用戶的表。

所以,當我使用一個關係到另一個對象時,(例如汽車)一切都很好。當我嘗試使用與另一位用戶的關係時,我收到如下錯誤:Cannot redeclare class App\Models\User.

我想我在這裏誤解了一些東西。

我覺得也許我應該'實例化'我的用戶的另一個版本(作爲'經理')...但我真的需要嗎?它比其他任何東西都更多。我不知道我甚至不知道該怎麼做。

請指點一些?

+0

您能否提供一些代碼?顯然你有多個用戶類的聲明 –

回答

0

這聽起來像你創建了兩個不同的「用戶」模式:

// /app/User.php: 

<?php namespace App; 
use Illuminate\Database\Eloquent\Model; 
class User extends Model 
{ 
    // ... 
    public function user() { 
     return $this->hasOne('App\Models\User'); 
    } 
} 


// /app/models/User.php: 

<?php namespace App\Models; 
use Illuminate\Database\Eloquent\Model; 
class User extends Model 
{ 
    // ... 
    public function user() { 
     return $this->belongsTo('App\User'); 
    } 
} 

相反,你想擁有屬於自己一個類:

// /app/User.php: 

<?php namespace App; 
use Illuminate\Database\Eloquent\Model; 
class User extends Model 
{ 
    // ... 
    public function parent() { 
     return $this->belongsTo('App\User'); 
    } 

    public function children() { 
     return $this->hasMany('App\User'); 
    } 
} 

然後在你的數據庫確保用戶表具有user_id屬性(編輯database/migrations/2014_10_12_000000_create_users_table.php):

$table->integer('user_id')->unsigned()->nullable(); 
$table->foreign('user_id')->references('id')->on('users'); 

現在您可以將用戶附加到另一個上:

<?php 

$manager = new User(); 
$employeeOne = new User(); 
$employeeTwo = new User(); 

$manager->children()->saveMany([ 
    $employeeOne, 
    $employeeTwo 
]); 

dd($employeeTwo->parent->name); // Manager's name