【问题标题】:Laravel Error leftJoin : Undefined property: Illuminate\Database\Eloquent\Collection::$idLaravel 错误 leftJoin:未定义属性:Illuminate\Database\Eloquent\Collection::$id
【发布时间】:2017-02-12 04:00:06
【问题描述】:

我在 laravel 上使用 leftJoin,但报错

未定义属性:Illuminate\Database\Eloquent\Collection::$id

这里是控制器的示例代码

$news = News::find($id)
            ->leftJoin('categories', 'news.category_id', '=', 'categories.id')
            ->get();

    //dd($news);

    return view('news.update')
    ->with('news', $news);

我一直在尝试使用 get()->first() 但它只显示第一条记录。 如果我像这样在刀片上使用 foreach,错误是一样的

<form class="form-horizontal" action="/news/{{$news->id}}" method="post" enctype="mulipart/form-data">
<select name="category_id">
    <option> - </option>
    @foreach($news as $news)
    <option value="{{ $news->category_id }}" selected>{{ $news->category }}</option>
    @endforeach 
</select> </form>

【问题讨论】:

    标签: php laravel laravel-5.3


    【解决方案1】:

    尝试这样做

    $news = DB::table('news')
              ->leftJoin('categories', 'categories.id', '=', 'news.category_id')
              ->select('news.*', 'categories.*')
              ->get();
    

    ->select('news.', 'categories.') // 从新闻和类别中选择所有记录

    <form class="form-horizontal" action="/news/{{$news[0]->id}}" method="post" enctype="mulipart/form-data">
      <select name="category_id">
          <option> - </option>
          @foreach($news as $news_data)
            <option value="{{ $news_data->category_id }}" selected>{{ $news_data->category }}</option>
          @endforeach 
      </select> 
    </form>
    

    【讨论】:

    • 嗨,它的工作:) 谢谢你的帮助,但你能解释一下 $news[0] 是什么意思吗?是这样调用数组的索引吗?集合 {#178 ▼ #items: array:4 [▼ 0 => {#168 ▶} 1 => {#180 ▶} 2 => {#186 ▶} 3 => {#187 ▶} ] }
    • $news[0] 从新闻数组中获取第一条记录
    猜你喜欢
    • 1970-01-01
    • 2014-11-23
    • 2016-07-08
    • 2016-06-02
    • 2017-03-05
    • 2018-10-22
    • 2018-11-19
    • 2019-08-12
    • 2020-05-04
    相关资源
    最近更新 更多