Laravel模型关系 一对一深入研究

发布时间 2023-11-05 22:11:49作者: 学无边涯

一,主表book

  class Book extends Model
{
//
protected $fillable=['title','price','num'];


public function bookCard(){
return $this->hasOne(BookCard::class);
}
}

二,关联表bookcard

class BookCard extends Model
{
//
protected $fillable=['number'];

public function book(){
return $this->belongsTo(Book::class);
}
}

三,主表和关联表如何写

$booklist=Book::find(1);
$res=$booklist->bookCard()->create([
'number'=>str_random(16),
]);