使用hasMany获取模型不适用于Laravel

时间:2017-06-09 10:46:25

标签: php laravel eloquent

我尝试在我的视图上打印与小队x相关的所有atleti,但方法In[13]: df.loc[df[6] == 'R',4] - df.loc[df[6] == 'F',4] Out[13]: 0 188 11.14 750 47.47 1330 60.03 1385 12.70 Name: 4, dtype: float64 总是返回我的空数组。

你有什么想法让这个工作吗?

在下面,您可以找到我的代码和我的数据库结构。 Squadra是英语团队。一个团队可以与许多atleti相关联(它代表玩家)。

我认为外键存在一些问题。

感谢您的帮助。

$squadra->atleti()

公共函数getSquadra($ id)     {         $ squadra = Squadra :: find($ id);

<?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
 */

这是 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 的输出 enter image description here

1 个答案:

答案 0 :(得分:0)

你发送atleti到视图,而不是squadra。尝试将控制器功能更改为:

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'));
}