I'm attempting to make a relationship with my users table and my news_posts table. When I look at the queries that are ran it shows the followoing.
select * from `news_posts` where `news_posts`.`deleted_at` is null and `id` = '1' limit 1
select * from `users` where `users`.`deleted_at` is null and `users`.`id` is null limit 1
So I'm trying to figure out why its saying NULL for the user.id.
I'm trying to access $news_post->author->first_name and $news_post->author->first_name.
<?php
class User extends Eloquent implements UserInterface, RemindableInterface {
public function post()
{
return $this->hasMany('NewsPost', 'user_id');
}
}
class NewsPost extends \Eloquent {
use SoftDeletingTrait;
protected $table = 'news_posts';
protected $fillable = [];
protected $dates = ['deleted_at'];
// DEFINE RELATIONSHIPS --------------------------------------------------
public function category()
{
return $this->belongsTo('NewsCategory');
}
public function author()
{
return $this->belongsTo('User');
}
}
table: news_posts
fields: id, user_id, title, content
table: users
fields: id, username, first_name, last_name
Try this
foreach (NewsPost::all() as $news_post)
{
echo $news_post->author->name;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.