简体   繁体   English

laravel eloquent model 是如何工作的?

[英]how does laravel eloquent model works?

in db Seller table and this table have seller_id and i have column paid and i want to get that data using model so consider in controller i use在 db Seller table ,该表有seller_id ,我有列已paid ,我想使用 model 获取该数据,所以在 controller 中考虑我使用

$seller = User::all();

in User ModelUser Model

public function benefits(){
     return $this->belongsTo('App\Seller' , 'seller_id');
}

in view在视野中

@foreach($sellers as $key => $seller)
    <td>{{ $seller->benefits->paid}}<\td>
@endforeach

but problem is that i am unable to get value from column paid in seller table my result is null how this query will work?但问题是我无法从卖家表中支付的列中获取价值我的结果是 null 这个查询将如何工作?

  • There is no $sellers variable in your code.您的代码中没有$sellers变量。
  • $seller is a collection, not a single record. $seller是一个集合,而不是单个记录。
  • Eager load benefits relationship to avoid making too many queries.急切的负载benefits关系,以避免进行过多的查询。
$sellers = User::with('benefits')->all();
@foreach ($sellers as $seller)
    <td>{{ $seller->benefits->paid }}<\td>
@endforeach

If seller_id is a column in the Seller model's table, then the benefits relationship in the User model is either hasOne or hasMany如果seller_idSeller模型表中的一列,则User model 中的benefits关系是hasOnehasMany

// User Model
public function benefits()
{
    return $this->hasOne('App\Seller', 'seller_id');
}
// Seller Model
public function user()
{
    return $this->belongsTo('App\User', 'seller_id');
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM