【问题标题】:Laravel - Property [comment] does not exist on this collection instanceLaravel - 此集合实例上不存在属性 [注释]
【发布时间】:2020-12-11 19:24:28
【问题描述】:

我对 laravel 模型关系有疑问。代码如下:

路线:

Route::get('/customers','Back\CustomerController@index')->name('admin.customer');

模型\Customer.php:

class Customer extends Model{
  public function getData(){
    return $this->hasMany('App\Models\Datapanel','name','name');
  }
}

模型\Datapanel.php:

class Datapanel extends Model{
   //
}

客户控制器.php:

class CustomerController extends Controller{
  public function index(){
    $customers=Customer::orderBy('created_at','desc')->get();
    return view('back.customer',compact('customers'));
  }
}

customer.blade.php:

@foreach ($customers as $customer)
<div class="tab-pane" id="{{$customer->name}}" role="tabpanel">
    {{$customer->getData}} //this line working and calling all data of the same name, but in array format.
    {{$customer->getData->comment}} //this line is what I want, but it doesn't work and gives the error Property [comment] does not exist on this collection instance
    {{$customer->getData->first()->comment}} //this line working, but calling first data and i want all the data of the same name.
    {{$customer->getData->all()->comment}} //I wish there was something like but it donesn't work.
</div>
@endforeach

【问题讨论】:

    标签: php laravel relationship


    【解决方案1】:

    由于getData 返回一个 HasMany 关系,它将是一个集合而不是单个记录。所以需要遍历集合来显示数据。见下文

    @foreach ($customers as $customer)
    <div class="tab-pane" id="{{$customer->name}}" role="tabpanel">
    
        <!-- Loop over each record in $customer->getData -->
        @foreach($customer->getData as $data)
            {{ $data->comment }} 
        @endforeach
    
    </div>
    @endforeach
    

    【讨论】:

    • 是的,你是个天才。感谢您的回复,我已经尝试解决了 2 天。
    • @ErdemSandıkçı 很高兴我能帮上忙。为了后续访问者的利益,请记住将答案标记为已接受/赞成。
    猜你喜欢
    • 2020-07-11
    • 2019-07-10
    • 2021-07-23
    • 2021-09-07
    • 2019-04-08
    • 2023-03-12
    • 2018-04-12
    • 1970-01-01
    相关资源
    最近更新 更多