我正在尝试在Player和Roleplay之间创建一个关系,并返回null。我知道它应该有效,因为下面的代码完美无缺:
Roleplay::find(Auth::user()->id);
并返回正确的数据,一整套正确的数据。
尝试以这种方式访问时:
Auth::user()->roleplay->user_id;
它不起作用,有人可以帮我找出原因吗?
你怎么知道它是空的?
因为刀片视图中的{{var_dump(Auth::user()->roleplay)}}
会返回EMPTY
在使用视图时,我也会得到一个未定义的错误。 角色扮演表(srp_user_statistics)的主键是user_id,播放器表(用户)的主键是id
这是代码:
Player:
<?php
namespace App\Database\Frontend\User;
use Hash;
use Eloquent;
use \Illuminate\Auth\Authenticatable;
use \Illuminate\Contracts\Auth\Authenticatable as Authentication;
class Player extends Eloquent implements Authentication
{
use Authenticatable;
protected $primaryKey = 'id';
protected $table = 'users';
public $timestamps = false;
protected $fillable = [];
public function setPasswordAttribute($value)
{
$this->attributes['password'] = Hash::make($value);
}
public function setUsernameAttribute($value)
{
return $this->attributes['username'] = $value;
}
public function roleplay()
{
return $this->hasOne('App\Database\Frontend\User\Roleplay', 'user_id');
}
}
角色扮演:
use Eloquent;
class Roleplay extends Eloquent
{
protected $primaryKey = 'user_id';
protected $table = 'srp_user_statistics';
public $timestamps = true;
protected $fillable = [];
public function user()
{
return $this->belongsTo('App\Database\Frontend\User\Player', 'user_id', 'id');
}
public function government_role()
{
return $this->belongsTo('App\Database\Frontend\Roleplay\GovernmentRole', 'government_id');
}
}
答案 0 :(得分:1)
我认为你应该添加&#39; id&#39;用户模型中的hasOne()
Roleplay::find(Auth::user()->id);
并删除&#39; id&#39;来自角色扮演模型中的belonsTo()。
旁注
这个工作
Roleplay::find(1); //$user->id returns an integer.
不保证您的关系设置正确。它只是
protected String doInBackground(Void... voids) {
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response;
String responseString = null;
try {
HttpPost post = new HttpPost(UrlRequest);
Gson gson = new Gson();
String jsonData = gson.toJson(_saleModel);
StringEntity entity = new StringEntity(jsonData);
entity.setContentType("application/json");
post.addHeader("Authorization", "bearer ".concat(mSession.getAccessToken()));
post.setHeader("Accept", "application/json");
post.setHeader("Content-Type", "application/json;charset=utf-8");
post.setEntity(entity);
response = httpclient.execute(post);
StatusLine statusLine = response.getStatusLine();
if(statusLine.getStatusCode() == HttpStatus.SC_OK){
ByteArrayOutputStream out = new ByteArrayOutputStream();
response.getEntity().writeTo(out);
responseString = out.toString();
out.close();
} else{
//Closes the connection.
response.getEntity().getContent().close();
throw new IOException(statusLine.getReasonPhrase());
}
} catch (ClientProtocolException e) {
//TODO Handle problems..
Log.e("Error", e.getMessage());
} catch (IOException e) {
//TODO Handle problems..
Log.e("Error",e.getMessage());
}
return responseString;
}