0

我是 Laravel 的新手,正在尝试探索。

我在尝试使用 eloquent 获取数据库中的数据时遇到问题。

我只想像这样获取数据。

SELECT id,name,status 
FROM tre
WHERE id = 1

这是我的控制器中的代码:

    /**
     * Display the specified resource.
     *
     * @param  \App\TRE  $tRE
     * @return \Illuminate\Http\Response
     */
    public function show(TRE $tRE)
    {
      return $tRE->load('tre_list');
    }

这是我的模型中的代码:

    public function tre_list(){

        return $this->belongsTo('App\TRE', 'id');

    }

但它只是返回null。

{tre_list: null}
tre_list: null

谁能帮我解决我的问题。

4

1 回答 1

0

从您的模型中删除此部分,因为您不需要它:

public function tre_list(){
    return $this->belongsTo('App\TRE', 'id');
}

在您的控制器的显示功能中,只需像这样返回:

/**
 * Display the specified resource.
 *
 * @param  \App\TRE  $tRE
 * @return \Illuminate\Http\Response
 */
public function show(TRE $tRE)
{
  return $tRE;
}

如果它返回 null,则具有该 ID 的 TRE 不存在。

于 2021-02-18T09:42:07.957 回答