Question

I can't figure how to relate these two tables.

I'm new to Laravel and ORM so it's kind of hard to me. Here's my 2 tables I'm trying to relate:

tables Tables are called: posts and post_categories And here are some of the code:

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();

}

So as you see. I pass values to post and when I save it's ok... but I can't add categories ID to another table...

And also I created dummie entries, and tried to get Post Categories values:

Route::get('/', function()
{
    $post = Post::find(5);
    echo $post->title;
    echo $post->categories()->id_1;
});

But it failed:

Undefined property: Illuminate\Database\Eloquent\Relations\HasOne::$id_1
Was it helpful?

Solution

OK first things first, You dont have to use PostCatagorie as your model name. Laravel features a pretty good pluralization class and can quite happily deal with Category or PostCategorie. Additionally, if you just call pc_id category_id (assuming a table name of category) you wont have to define any foreign keys which will make life a bit simpler until you get to grips with the basics.

When you create any kind of object (e.g $post) you can check if its relations are attached using dd($post); you can drill down further into these relations with:

echo '<pre>';
print_r($post);
echo '</pre>;

This together will allow you to see if what you are trying to do is actually working and view the structure of your result object.

I'm not entirely sure what you mean by "I cant add categories id to another table", and you seem to be saving the data ok... so I'll skip that bit. Please clarify the question if you need more info.

Once you have got the relationships set up and got some data in there you would have to load the two models together like so to get an object with the attached relationship:

$post = Post::with('Category')->find(5);

You will then be able to access your category object as $post->Category and from there any of its properties, e.g. $post->Category->id

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top