【发布时间】:2016-11-08 21:33:04
【问题描述】:
这是我的帖子表
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreatePostsTable extends Migration
{
public function up()
{
Schema::create('posts', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_id')->unsigned();
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
$table->integer('prf_id')->unsigned();
$table->foreign('prf_id')->references('id')->on('profiles')->onDelete('cascade');
$table->longText('status');
$table->timestamps();
});
}
public function down()
{
Schema::drop('posts');
}
}
这是我的帖子模型:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
protected $table='posts';
protected $fillable = ['status'];
protected $hidden = [];
public function profile(){
return $this->belongsTo('App\Profile');
}
public function user(){
return $this->belongsTo('App\User');
}
}
这是个人资料模型
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Profile extends Model
{
protected $table='profiles';
protected $fillable = ['user_id','name','position','roles','username','college','phone','location','graduation','skill'];
protected $hidden = [];
public function posts(){
return $this->hasMany('App\Post');
}
}
这是用户模型
<?php
namespace App;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
protected $fillable = [
'fname','lname', 'email','sex', 'password','user_id','roles'
];
/**
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected $hidden = [
'password', 'remember_token',
];
public function posts(){
return $this->hasMany('App\Post');
}
}
当我尝试 {{$status->user->fname}} this.its 显示正确的值但是当我尝试 {{$status->profile->username} } 这个,每次它显示我 试图获取非对象的属性(视图:C:\xampp\htdocs\abc\resources\views\pages\profile.blade.php) 我真的不知道为什么:(
【问题讨论】:
-
显示你正在获取的代码
$status? -
'公共函数myprofile(请求$request){$id=$request->prf; $user=User::where('id','=',$id)->first(); $u_id=$user->user_id; $all=Profile::where('id','=',$id)->first(); $tasks=Task::where('user_id','=',$u_id)->get(); $user=User::where('id','=',$id)->first(); $statuses=Post::all(); return view('pages.profile',compact('all','tasks','user','statuses')); } '
-
@leo 作为问题的编辑请。
-
您的数据库没有使用表 profiles 的默认键,您可以显示表键 ID 吗? belongsTo('App\Profile') 尝试使用 profile_id 而不是 prf_id