当数据庞大时,我们不会把所有资料都存在同一个资料表,会依照资料类型做分类,例如:使用者资料的users table、文章资料的posts table,这时候资料的关联就很重要,必须有方法让我们知道这篇文章是哪个User所发布,所以在这边简单介绍Laravel Model要如何撰写Relationship.
database/migration/2021_09_19_082930_create_posts_table.php
规划了Post table有一个user_id栏位,就是为了能够知道这篇文章是谁发的,来做资料库的关联/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('posts', function (Blueprint $table) {
$table->id();
$table->unsignedBigInteger('user_id')->comment('发文者');
$table->string('title')->unique()->comment('标题');
$table->string('content')->comment('内文');
$table->timestamps();
});
}
# App/Models/User.php
/**
* 取得使用者的文章
*/
public function posts()
{
return $this->hasMany(Post::class);
}
/**
* Define a one-to-many relationship.
*
* @param string $related
* @param string|null $foreignKey
* @param string|null $localKey
* @return \Illuminate\Database\Eloquent\Relations\HasMany
*/
public function hasMany($related, $foreignKey = null, $localKey = null)
{
$instance = $this->newRelatedInstance($related);
$foreignKey = $foreignKey ?: $this->getForeignKey();
$localKey = $localKey ?: $this->getKeyName();
return $this->newHasMany(
$instance->newQuery(), $this, $instance->getTable().'.'.$foreignKey, $localKey
);
}
/**
* 取得文章数量
*
* @return mixed
*/
public function getPostList()
{
try {
$user = Auth::guard('api')->user();
$result = User::find($user->id);
return $result->posts;
} catch (Exception $e) {
dd($e);
}
}
其余情境可以参考官方文件,写得非常详细,其实按照需求去置换function name就好
>>: 第 06 天 有甚麽事先练再说( leetcode 105 )
什麽是 Singleton Pattern? 整个程序运作只会有此一个物件,不会创建第二个重复的物件...
什麽是 Idle Detection API Idle Detection API 的设计是当 Ap...
你以为JS拿来就乖乖照着我们打的一行一行跑吗?太天真了,我说我~~ 变数怎麽存,存哪里,在哪里叫得到...
今天来说说温湿度读取的部分吧,首先来看看这颗的Datasheet: https://www.sila...
什麽是Flutter 正如第一篇文章所说的 Flutter 是一个「框架」,可以用来开发跨平台原生的...