belongsTo() 函数不起作用
belongsTo() function not working
我正在尝试与我的角色 table 和帐户 table 建立关系,但是当我添加 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;
}
}
Table结构:
accounts:
- username
characters:
- account_name //foreign key
$players
的结果只是字符数据。为什么账户数据没有添加进去?
如果我理解你正在尝试做的是你正在尝试获得一个玩家和他们的所有角色。
尝试
function index(){
$player = Account::find(1);
return $player->characters;
}
找到一个角色的账号
$caracter = Character::find(1);
return $caracter->account;
试试这个:
//Get online status
public function account(){
return $this->belongsTo(Account::class, 'account_name', 'username');
}
我正在尝试与我的角色 table 和帐户 table 建立关系,但是当我添加 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;
}
}
Table结构:
accounts:
- username
characters:
- account_name //foreign key
$players
的结果只是字符数据。为什么账户数据没有添加进去?
如果我理解你正在尝试做的是你正在尝试获得一个玩家和他们的所有角色。
尝试
function index(){
$player = Account::find(1);
return $player->characters;
}
找到一个角色的账号
$caracter = Character::find(1);
return $caracter->account;
试试这个:
//Get online status
public function account(){
return $this->belongsTo(Account::class, 'account_name', 'username');
}