我不知道如何关联这两个表。
我是 Laravel 和 ORM 的新手,所以对我来说有点难。这是我要关联的两张表:
表被称为:posts 和 post_categories 下面是一些代码:
class Post extends Eloquent {
public function categories()
{
return $this->hasOne('PostCategorie');
}
}
class PostCategorie extends Eloquent {
protected $table = 'post_categories';
public function post()
{
return $this->belongsTo('Post', 'pc_id');
}
}
public function postCreate()
{
$validator = Validator::make(Input::all(), Post::$rules);
if ($validator->fails())
{
return Redirect::action('PostsController@getCreate')->withInput()->withErrors($validator);
}
// Else add to DB
$categories = Input::get('categories');
$post = new Post;
$post->user_id = Auth::user()->id;
$post->title = Input::get('title');
$post->text = Input::get('text');
$post->categories()->id_1 = $categories[0];
$post->save();
}
所以如你所见。我将值传递给发布,当我保存它时就可以了......但我无法将类别 ID 添加到另一个表......
我还创建了虚拟条目,并尝试获取 Post Categories 值:
Route::get('/', function()
{
$post = Post::find(5);
echo $post->title;
echo $post->categories()->id_1;
});
但它失败了:
Undefined property: Illuminate\Database\Eloquent\Relations\HasOne::$id_1