I'm trying to build a simple news feed for posts in Laravel with Eloquent.
I basically want to retrieve all Posts...
- where I am author
- where people I follow are author (followable)
- where people I follow have commented on
- where people with same field_id are author
- where poeple with same school_id are author
in one query.
As I never worked intensivly with joined/combined SQL queries, any help on this is greatly appreciated!
My Tables
users
table
+----+
| id |
+----+
posts
table
+----+-----------+-------------+
| id | author_id | author_type |
|----|-----------|-------------|
| | users.id | 'App\User' |
+----+-----------+-------------+
comments
table
+----+----------------+------------------+-----------+-------------+
| id | commentable_id | commentable_type | author_id | author_type |
|----|----------------|------------------|-----------|-------------|
| | posts.id | 'App\Post' | users.id | 'App\User' |
+----+----------------+------------------+-----------+-------------+
schoolables
table
+---------+-----------+----------+
| user_id | school_id | field_id |
+---------+-----------+----------+
followables
table
+-------------+---------------+---------------+-----------------+
| follower_id | follower_type | followable_id | followable_type |
|-------------|---------------|---------------|-----------------|
| users.id | 'App\User' | users.id | 'App\User' |
+-------------+---------------+---------------+-----------------+
My Models
class Post extends Model
{
/**
* @return \Illuminate\Database\Eloquent\Relations\MorphTo
*/
public function author()
{
return $this->morphTo();
}
/**
* @return \Illuminate\Database\Eloquent\Relations\MorphMany
*/
public function comments()
{
return $this->morphMany(Comment::class, 'commentable');
}
}
class Comment extends Model
{
/**
* @return \Illuminate\Database\Eloquent\Relations\MorphTo
*/
public function author()
{
return $this->morphTo();
}
/**
* @return \Illuminate\Database\Eloquent\Relations\MorphTo
*/
public function commentable()
{
return $this->morphTo();
}
}
class User extends Model
{
/**
* @return \Illuminate\Database\Eloquent\Relations\MorphMany
*/
public function posts()
{
return $this->morphMany(Post::class, 'author')->orderBy('created_at', 'desc');
}
/**
* @return \Illuminate\Database\Eloquent\Relations\MorphMany
*/
public function comments()
{
return $this->morphMany(Comment::class, 'author')->orderBy('created_at', 'desc');
}
/**
* @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
*/
public function schoolables()
{
return $this->hasMany(Schoolable::class);
}
/**
* @return \Illuminate\Database\Eloquent\Relations\MorphMany
*/
public function following()
{
return $this->morphMany(Followable::class, 'follower');
}
}
via Chebli Mohamed
Aucun commentaire:
Enregistrer un commentaire