donglinli2027 2015-04-21 12:17
浏览 126
已采纳

Laravel拥有许多通过和懒惰的渴望加载

I have the following models set up in Laravel 5 (everything is namespaced into App\Models, but I've removed that for readability) :

class Client extends Model {
    public function templates() { return $this->hasMany('Template'); }
    public function documents() { return $this->hasManyThrough('Template', 'Document'); }
    public function users() { return $this->hasMany('User'); }
}

class Template extends Model {
    public function client() { return $this->belongsTo('Client'); }
    public function documents() { return $this->hasMany('Document'); }
}

class Document extends Model {
    public function template() { return $this->belongsTo('Template'); }
}

In a controller, I have the current user:

$user = \Auth::user();
$client = $user->client;

I want to show a list of

  • the templates for a client
  • the documents for a client, separately, not grouped by template

It seems easy enough; I already have both of the relations needed. The question is, if I lazy eager load templates and documents onto $client, do I still need to eager load templates.documents (hasManyThrough) or is Laravel smart enough to realise?

$client->load( 'templates', 'documents' );
// or...
$client->load( 'templates', 'templates.documents' );
// or...
$client->load( 'templates', 'documents', 'templates.documents' );
  • 写回答

2条回答 默认 最新

  • drap5081683 2015-04-21 12:59
    关注

    I've just found that it's possible to see if a relation is loaded, so I've run artisan tinker and tested:

    $c = Client::first();
    array_key_exists('documents', $c->getRelations()); // false
    
    // Loading `templates` and `documents` separately doesn't load `templates.documents`
    $c = Client::first();
    $c->load('templates', 'documents');
    array_key_exists('documents', $c->getRelations()); // true
    array_key_exists('documents', $c->templates->first()->getRelations()); // false
    
    // Loading `documents.templates` doesn't load `documents` or `templates`
    $c = Client::first();
    $c->load('templates.documents');
    array_key_exists('documents', $c->templates->first()->getRelations()); // true
    array_key_exists('documents', $c->getRelations()); // false
    

    So I guess the definitive answer is that if you have a hasManyThrough you must explicitly load any relation you'll access - it's not smart enough to realise that it's already loaded the relation for you.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!