一对多关联

2018-03-11 10:54:00 阅读:4 编辑

1. 每个用户有多篇文章

1).user.php 添加代码

 public function posts ()
    {return $this->hasMany (Post::class)->select (["id","user_id","title"]);
    }

2. 测试代码

function query_end ()
{$queries = DB::getQueryLog ();
    foreach ($queries as $i=>$query)
    {Log::debug ("Query $i:" . JSON_encode ($query));
    }
}
Artisan::command ('linson:query_one',function (){query_start ();
    // Run your queries
    $res = \App\User::with ('profile')->first (["id"]);
    print_r ($res->toArray ());
    // Then to retrieve everything since you enabled the logging:
    query_end ();});

Artisan::command ('linson:query_many',function (){query_start ();
    // Run your queries
    $res = \App\User::with (['posts'=>function ($query){$query->orderBy ("id","asc");
    }])->first (["id"]);
    print_r ($res->toArray ());
    // Then to retrieve everything since you enabled the logging:
    query_end ();});
当然,由于所有关联同时也是查询构建器,我们可以添加更多的条件约束到通过调用 posts 方法获取到的文章上:
User::first ()->posts ()->where ("id",">=", 10)->get ();
with 可以带多个
 User::with ("posts","profile")->first ();

一对多 ( 逆向)

1). 在 Posts.php 添加代码

 public function user ()
    {return $this->belongsTo (User::class)->select (["id","email"]);
    }

2). 测试代码

λ pa tinker
Psy Shell v0.8.17 (PHP 7.0.10 鈥?cli) by Justin Hileman
>>> App\Post::with ("user")->first ();
=> App\Post {#747
     id: 1,
     user_id: 1,
     title: "Ducimus asperiores fugiat reprehenderit et officia quos qui.",
     created_at: "2018-03-11 02:38:54",
     updated_at: "2018-03-11 02:38:54",
     user: App\User {#751
       id: 1,
       email: "mayer.monte@example.com",
     },
   }
>>>