2017-06-09 5 views
0

私はsquadra xに関連付けられているすべてのatletiを印刷しようとしていますが、$squadra->atleti()メソッドは常に私のantの空の配列を返します。hasManyがLaravelで動作していないモデルを取得

これを行うにはいくつかのアイデアがありますか?

下に私のコードと私のDB構造を見つけることができます。 スクアドラは英語のチームです。 1つのチームは多くのアトレティ(それは選手を表す)に関連付けることができます。

私は外来キーにいくつかの問題があると思います。

ありがとうございました。

<?php 
//Squadra Model 
namespace App\Models; 

use Illuminate\Database\Eloquent\Model; 

class Squadra extends Model 
{ 
protected $connection = 'custom_mysql'; 
protected $table = 'squadra'; 
/** 
* Get the Allenatore for the Squadra. 
*/ 
public function allenatore() 
{ 
    return $this->belongsTo('App\Models\Allenatore'); 
} 

/** 
* Get the Atleta for the Squadra. 
*/ 
public function atleti() 
{ 
    return $this->hasMany('App\Models\Atleta'); 
} 
} 

<?php 
//Atleta Model 
namespace App\Models; 

use Illuminate\Database\Eloquent\Model; 

class Atleta extends Model 
{ 
protected $table = 'atleta'; 
protected $connection = 'custom_mysql'; 
/** 
* Get the Atleta for the Squadra. 
*/ 
public function squadra() { 
    return $this->belongsTo('App\Models\Squadra'); 
} 
} 

<?php 
//Controller 
namespace App\Http\Controllers; 

use Illuminate\Http\Request; 

use App\Http\Requests; 

class AtletaController extends Controller 
{ 
/** 
* Display a listing of the resource. 
* 
* @return \Illuminate\Http\Response 
*/ 

パブリック関数getSquadra($ ID)と {$スクアドラ=スクアドラ::検索($ ID)と、

return view('custom.squadra.dettaglio', compact('squadra')); 
} 

//View 
@foreach($squadra->atleti() as $atleta) 

<tr class="success"> 

<td>{{ $atleta->id }}</td> 
<td>{{ $atleta->nome}}</td> 
<td>{{ $atleta->cognome}}</td> 
</tr> 
@endforeach 

ここでは、あなたの代わりにスクアドラの、ビューにアトレティを送信しているdd($squadra) enter image description here

+0

インデックス機能でdd($ athleti)を使用できますか?データベースにデータが保存されていますか? – utdev

+0

ここで@utdevを見て、私はdd($ squadra)の出力コードで質問を編集しました。はい、私はいくつかのデータをDBに格納しています。 –

答えて

0

の出力です。

public function index() 
{ 
    $squadra = Squadra::firstOrFail(); // You need a paremeter in a route that defines which squadra to show. This will show the first one. 

    return view('custom.atleta.index', compact('squadra')); 
} 
+0

コントローラーに混乱があります。新しい固定コード@piscatorを見てください。しかし、何も変わっていない、それはまだ空です。モデルコードは正しいですか? –

+0

@ jack_0あなたの意見で '$ squadra-> atleti()'を '$ squadra-> atleti'または' $ squadra-> atleti() - > get() 'に変更します。 – piscator

+0

ありがとうございます。今はうまくいく。 2つの表現の違いは何ですか? –

関連する問題