Php 拉维尔问题
我不知道如何把这两张表联系起来 我是拉威尔和奥姆的新手,所以这对我来说有点难。 以下是我试图关联的两个表格: 表被称为:posts和post_类别 下面是一些代码:Php 拉维尔问题,php,mysql,orm,laravel,Php,Mysql,Orm,Laravel,我不知道如何把这两张表联系起来 我是拉威尔和奥姆的新手,所以这对我来说有点难。 以下是我试图关联的两个表格: 表被称为:posts和post_类别 下面是一些代码: class Post extends Eloquent { public function categories() { return $this->hasOne('PostCategorie'); } } class PostCategorie extends Eloquent { protecte
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();
}
如你所见。我将值传递给post,保存后就可以了。。。但我无法将类别ID添加到另一个表中
我还创建了虚拟条目,并尝试获取帖子类别值:
Route::get('/', function()
{
$post = Post::find(5);
echo $post->title;
echo $post->categories()->id_1;
});
但它失败了:
Undefined property: Illuminate\Database\Eloquent\Relations\HasOne::$id_1
首先,你不必使用PostCatagorie作为你的模型名。Laravel拥有一个相当好的多元化类,可以非常愉快地处理分类或后分类。此外,如果您只需调用
pc\u id
category\u id(假设表名为category),则不必定义任何外键,这将使您的生活更加简单,直到您掌握了基本知识
创建任何类型的对象(例如$post)时,可以使用dd($post)检查其关系是否已附加代码>您可以使用以下工具进一步深入了解这些关系:
echo '<pre>';
print_r($post);
echo '</pre>;
然后,您将能够以$post->category
的形式访问类别对象,并从中访问其任何属性,例如$post->category->id
我什么都不懂=/。。。。那么,我为什么要使用('Category')->find(5);如果我已经有了关系。。。那“类别”是什么???如果我有后分类
$post = Post::with('Category')->find(5);