Laravel hasOne vs EmiratesTo返回null

时间:2019-08-29 19:00:27

标签: php laravel laravel-5

我对Laravel并不陌生,我试图返回两个有关系的表的值,但是我收到了null

在我的 Controller 中,我正在传递with('image')

$products = Produtos::select('codigo', 'descricao', 'CT', 'Fotos')->with('image')->take(2)->get();
return response()->json($products);

图片模型

class Objetos extends Model
{
    protected $table = 'Imagens';

    public function produtos(){
        return $this->belongsTo(\App\Produtos::class);
    }
}

产品型号

class Produtos extends Model
{
    public function image(){
        return $this->hasOne(\App\Objetos::class, 'Chave');
    }
}

具有关系的列为:

Objetos.Chave = Produtos.id

我看不到我的错误,但我认为可能是因为我在hasOnebelongsTo中传递了参数。

注意:我正在访问外部数据库(MS SQL),但我认为这不是问题。

1 个答案:

答案 0 :(得分:1)

首先,您应该更改Image模型上的关系,您的foreign key不遵循laravel naming conventions,您必须像在Product上那样指定它模型,即:

public function produtos(){
    return $this->belongsTo(\App\Produtos::class, 'Chave');
}

但是真正的问题出在您的查询中:

Produtos::select('codigo', 'descricao', 'CT', 'Fotos')->with('image')->take(2)->get();

在这里您错过了将id添加到 selected 字段中的问题,因此laravel无法eager load相关的Image模型,因此您应该像这个:

Produtos::select('id', 'codigo', 'descricao', 'CT', 'Fotos')->with('image')->take(2)->get();

恕我直言,我的建议是不要用select()限制在模型上检索到的字段,如果存在适当的关系,则可能会发生此类错误。