belongsTo()函数不起作用

时间:2017-02-10 11:57:59

标签: laravel relation

我正在尝试与我的字符表和帐户表建立关系,但是当我添加belongsTo()方法时,我没有看到添加帐户的数据。

所以这是我的角色模型:

class Character extends Model
{
    //Get players by level
    public function scopeGetPlayersByLevel($query){
        return $query->orderBy('level', 'desc')->get();
    }

    //Get players by zulie
    public function scopeGetPlayersByZulie($query){
        return $query->orderBy('zuly', 'desc')->get();
    }

    //Get online status
    public function account(){
        return $this->belongsTo(Account::class, 'username', 'account_name');
    }
}

帐户模型:

class Account extends Model
{
    //Get online players
    public function scopeGetOnlinePlayers($query){
        return $query->where('online', 1);
    }

    //Get online staff
    public function scopeGetOnlineStaff($query){
        return $query->where('online', 1)->where('accesslevel', 350);
    }

    public function characters(){
        return $this->hasMany(Character::class, 'account_name', 'username');
    }
}

我在控制器中添加变量,如下所示:

使用App \ Character;

class RankingController extends Controller
{
    function index(){
        $players = Character::find(100);
        return $players;
    }
}

表格结构:

accounts:
  - username

characters:
  - account_name //foreign key

$players的结果只是字符数据。为什么帐户数据不会添加到它?

2 个答案:

答案 0 :(得分:1)

如果我明白你要做的是你想要一个玩家及其所有角色。

function index(){
    $player = Account::find(1);
    return $player->characters;
}

找到角色的帐号

$caracter = Character::find(1);
return $caracter->account;

答案 1 :(得分:1)

试试这个:

//Get online status
    public function account(){
        return $this->belongsTo(Account::class, 'account_name', 'username');
    }