我似乎遇到了問題。我有我的索引控制器,做到這一點:Laravel 5 - 試圖獲取非對象的屬性
public function index()
{
$projects = Project::dateDescending()->get();
return view('projects.index', compact('projects'));
}
如果我傾倒$projects
,我可以看到我有兩個對象。一個項目的屬性是
"clientId" => 1
一個Project
有一個Client
和Client
屬於Project
,這是所有設置。在我的索引視圖,我這樣做:
@foreach($projects as $project)
<tr>
{!! Form::open(array('class' => 'form-inline', 'method' => 'DELETE', 'route' => array('projects.destroy', $project->id))) !!}
<td>{{ $project->id }}</td>
<td>{{ $project->clientId->clientName }}</td>
<td>{{ $project->clientStatus }}</td>
<td>{{ $project->projectName }}</td>
<td>{!! link_to_route('projects.show', 'Show', array($project->id), array('class' => 'btn btn-info')) !!}</td>
<td>{!! link_to_route('projects.edit', 'Edit', array($project->id), array('class' => 'btn btn-info')) !!}</td>
<td>{!! Form::submit('Delete', array('class' => 'btn btn-danger')) !!}</td>
{!! Form::close() !!}
</tr>
@endforeach
出於某種原因,我得到一個錯誤,因爲這條線的
<td>{{ $project->clientId->clientName }}</td>
但我可以有機會獲得clientName
因爲建立的關係?
這是奇怪的部分。如果我只有一個項目在數據庫中,客戶端名稱顯示正常。只有當我添加第二個項目時,我得到這個錯誤。
可能是什麼造成的?
UPDATE
我的遷移是像這樣:
Schema::create('clients', function (Blueprint $table) {
$table->increments('id');
$table->string('clientName')->default('');
$table->string('contactEmail')->default('');
$table->string('slug')->default('');
$table->timestamps();
});
Schema::create('projects', function (Blueprint $table) {
$table->increments('id');
$table->integer('clientId')->unsigned()->default(0);
$table->foreign('clientId')->references('id')->on('clients')->onDelete('cascade');
$table->string('contactName')->default('');
$table->string('projectName')->default('');
$table->timestamps();
});
我的客戶模型:
class Client extends Model
{
protected $table = 'clients';
protected $guarded = [];
public function project()
{
return $this->belongsTo('App\Project', 'clientId');
}
}
我的項目模型:
class Project extends Model
{
protected $table = 'projects';
protected $guarded = [];
public function scopeDateDescending($query)
{
return $query->orderBy('created_at','DESC');
}
public function client()
{
return $this->hasOne('App\Client', 'id');
}
}
我有更新的詳細信息,OP,謝謝 –
在你的項目模型中試試這個, public function client() return $ this-> hasOne('App \ Client','id','clientId'); } 然後按照上面所述的方式引用您的客戶。 –