I am building a social network where the user will have a stream like Twitter of all the posts from the people that they follow.
What is the best way to query this with Laravel Eloquent?
I have 3 tables
users
id | username | etc...|
relationships
id | user_id |follows_id |
posts
id | user_id | post|
You may try something like this (Basic Idea):
users
id | username | etc...
posts
id | user_id | post_content
favorites (relationships)
id | user_id |post_id
Define the Post class something like this:
class Post extends Eloquent {
//...
public function favorites()
{
return $this->hasMany('Favorite');
}
}
Define the favorite class:
class Favorite extends Eloquent {
// ...
}
Query for the posts:
$posts = Post::whereHas('favorites', function($q) {
$q->where('user_id', Auth::user()->id);
})->get();
Related
I have two table users and customer_details. I want to get users which are created by Auth::user(). The created_by column is in customer_details table.
User Table
| id | name | email | status |
|-----------------------------------------------|
| 1 | Admin | admin#email.com | Active |
| 2 | Customer | user#email.com | Active |
CustomerDetails Table
| id | user_id | added_by | address |
|-------------------------------------------|
| 1 | 2 | 1 | NY City |
This is my query
$customers = User::role('Customer')->whereIn('status', ['Active'])->get();
Want to get records where added_by is current auth user
$customers = User::role('Customer')->whereIn('added_by', Auth::id())->get();
I think this should help
here we are using Auth::id() to get the id of the current user and then using eloquent to search for it.
I am considering that here added_by column contains the ID;
Create a relation in your CustomerDetail model:
public function addedBy()
{
return $this->belongsTo(User::class, 'added_by');
}
Then, you can query using this relation:
CustomerDetail::whereHas('addedBy', function($query) {
return $query->where('id', auth()->id());
})->get();
This query returns all customer created by the user current logged in.
To get all users with it's customers created by the current logged in user, add a new relation, now to the user model:
public function customerDetail()
{
return $this->hasOne(CustomerDetail::class, 'added_by');
}
and query users with customers created byt the logged in user:
User::role('Customer')->whereHas('customerDetail', function($query) {
return $query->where('added_by', auth()->id());
})
->whereIn('status', ['Active'])
->get();
Problem
I created a simple friendship relationship for my Laravel app which all worked ok until I noticed that when I queried the friendship of a user it would only search the current user on the UID1 field.
Since friendships are in essence a two-way relationship, Im trying to find a way in a laravel Model to retrieve ALL friendships relations by multiple columns.
Current Implementation
public function friends()
{
return $this->belongsToMany( App\Modules\Users\Models\User::class ,'friends', 'uid1');
}
Ideal Implementation
public function friends()
{
$a = $this->belongsToMany( App\Modules\Users\Models\User::class ,'users_friends', 'uid1');
$b = $this->belongsToMany( App\Modules\Users\Models\User::class ,'users_friends', 'uid2');
return combine($a,$b);
}
Table Structure
+----------------------+
| users table |
+----------------------+
+----| id: primary UserID |
| | fname: string |
| +----------------------+
|
|
| +----------------------+
| | friends table |
| +----------------------+
| | id: primary iD |
| | |
+----| uid1: user_id |
| | |
+----| uid2: user_id |
+----------------------+
The current implementation will only result in 1 of these records returning if the Current UserID = 1 as per the data in the friends table below.
+-------------------------------+
| friends table (data) |
+--------|---------|------------+
| id | uid1 | uid2 |
+--------|---------|------------+
| 1 | 1 | 7 |
| 2 | 7 | 1 |
| 3 | 9 | 1 |
+-------------------------------+
User Model
<?php
namespace App\Modules\Users\Models;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
protected $table = 'users';
protected $fillable = [
'username', 'email', 'password', .... .
];
public function friends()
{
return $this->belongsToMany( App\Modules\Users\Models\User::class ,'users_friends', 'uid1');
}
Environment
Server = Homestead/linux
PHP = 7
MySQL
Update
I have a FriendShip helper class I created which does something similar, however in this function I pass in the UserID explicitly
Friendship::where( [
[ 'uid1' ,'=', $uid],
])->orWhere( [
[ 'uid2', '=', $uid]
])->all();
You can add additional conditions when you're declaring relationship by simply chaining it.
<?php
//...
class User extends Model {
//...
public function friends() {
return $this->hasMany(/*...*/)->orWhere('uid2', $this->id);
}
//...
But keep in mind that eloquent is not grouping the first conditions of relation in parenthesis so you might end with SQL that will not work as expected in some cases (if using or, and should be fine)
For example the above might result in a SQL that looks like this
SELECT * FROM users_friends WHERE uid1 = ? AND uid1 IS NOT NULL OR uid2 = ?
Which is a correct SQL statement but without grouping you will not get the result that you're expecting.
Another way is to use accessor and two separate relationships
<?php
//...
public function friends1() {
return $this->belongsToMany(User::class, 'users_friends', 'uid1');
}
public function friends2() {
return $this->belongsToMany(User::class, 'users_friends', 'uid2');
}
public function getFriendsAttribute() {
return $this->friends1->merge($this->friends2);
}
//...
But this way you get two separate trips to DB.
Situation: In my laravel project. Below are the 4 Tables. movie_venue is a pivot table of movies and venues. I need to access the showtimes using movie model.
$movie = $this->model->find($movie_id);
$venues = $movie->venues;
Using eloquent relations i can access the venues list. But cant able to create a relationship for getting showtimes from movie model.
| movies | venues | movie_venue | showtimes |
----------------------------------------------------|
| id | id | id |id |
| name | name | movie_id |movie_venue_id |
| .... | .... | venue_id |time |
I assume you're using a One-to-many relationship for Venues to Showtimes?
You could try something like:
foreach ($movies->venues as $venue) {
foreach ($venue->showtimes as $showtime) {
//do something with your showtime.
}
}
By the way: wouldn't it make more sense to start from the venue and than access Showtimes?
UPDATE
Based on your comment, you can try something like this:
$movie = Movie::find($id);
$venues = $movie->venues;
foreach ($venues->showtimes as $showtime) {
// Here you'll get the showtimes per venue.
}
Hi I'm using Laravel and Eloquent in order to store users, there profile and there assigned roles. My table structure is as follows;
users
id | username | email | password | created_at | updated_at
profiles
id | user_id | firstname | created_at | updated_at
roles
id | name
assigned_roles
id | user_id | role_id
I'm trying to select all users where there role name is equal to admin. But when I do the following I get an empty array:
return \User::with('profile')->join('assigned_roles', function ($join) {
$join->where('assigned_roles.user_id', '=', 'users.id');
})->get();
Any ideas what I'm doing wrong?
Also I am using Zizaco Entrust and Confide https://github.com/Zizaco/entrust/tree/1.0
In order to fetch users that have admin role you need to use Eloquent's whereHas() method:
$admins = \User::with('profile')
->whereHas('assigned_roles', function($query) {
$query->whereName('admin');
})
->get();
I assume you have assigned_roles relation defined. If not, add many-to-many relation between your users and roles:
public function assigned_roles() {
return $this->belongsToMany('\Your\Model\Namespace\Role', 'assigned_roles', 'user_id', 'role_id');
}
I'm not so good at making queries using Laravel Eloquent. I've two tables
stories table
------------------------------------------------------------------
id | title | body | author_id |...
------------------------------------------------------------------
1 | Story 1 | Once a.. | 2
2 | Story 2 | There is | 4
3 | Something | You are. | 2
activities table
------------------------------------------------------------------
id | story_id | liker_id |...
------------------------------------------------------------------
1 | 2 | 2
Here author_id & liker_id are actually user_id. I want to get the Stories authored and liked by a specific user to display these stories in his profile.
I want to use the Eloquent ORM. I tried something like this using query builder
$stories = DB::table('stories')
->join('activities', function($join)
{
$join->on('stories.author_id', '=', 'activities.liker_id')
})
->where('stories.author_id', $author_id)
->get();
return $stories;
I can get story_id for a specific liker_id by join but couldn't get the details from stories table using story_id in a Single query.
Here is simple method with query builder to get Stories authored and liked by a specific user
$author_id = 1;
$stories = DB::table('stories')
->join('activities', 'stories.author_id', '=', DB::raw('activities.liker_id AND stories.id = activities.story_id'))
->Where('stories.author_id', $author_id)
->get();
//select * from `stories` inner join `activities` on `stories`.`author_id` = activities.liker_id AND stories.id = activities.story_id where `stories`.`author_id` = 1"
with Eloquent you can do as following create 2 model file
1. Story model (Story.php)
2. Activity Model (Activity.php)
Story.php
class Story extends Eloquent {
public function activities()
{
return $this->hasMany('Activity');
}
}
Activity.php
class Activity extends Eloquent {
public function story()
{
return $this->belongsTo('Story');
}
}
than you can write function within Story to get data as your need
$stories = Story::with('activities')
->where(DB::raw('stories.id = activities.story_id'))
->Where('stories.author_id', $author_id)
->get();
// haven't tested with eloquent but it should work