I have a table without 'primary ID', ex.
+---------+----------+------------+------------+
| user_id | point_id | created_at | updated_at |
+---------+----------+------------+------------+
And I have records:
1 ..| 200 | (date) | (date)
14 | 300 | (date) | (date)
1 ..| 200 | (date) | (date)
Now I want delete only one record to get:
1 ..| 200 | (date) | (date)
14 | 300 | (date) | (date)
I tryied:
UserPoint::where( 'point_id', $reqId )->where( 'user_id', $userId )->first()->delete();
But it always remove all record with this params ... Anyone can help?
EDIT: My UserPoint model
use Illuminate\Database\Eloquent\Model;
class UserPoint extends Model {
protected $table = 'point_user';
public function scopeUsed($query){
return $query->where('amount', '<', 0);
}
public function scopeEarned($query){
return $query->where('amount', '>', 0);
}
public function about(){
return $this->hasOne('\App\Point', 'id', 'point_id');
}
}
The way you are trying to achieve this deletion is somewhat wrong as it does not follow the rules of data integrity . Deleting a child table in your case would impose what we call an orphaned table.
However the correct way of deleting that record would be to first associate this table to its parent related table in this case as below:
Class User extends Model {
public function points() {
return $this->hasMany(UserPoint::class)
}
}
then in your UserPoint Class or Model you then need to map your relation.
class UserPoint extends Model {
protected $table = 'point_user';
// I have added this part
public function users() {
return $this->belongsTo(User::class)
}
public function scopeUsed($query){
return $query->where('amount', '<', 0);
}
public function scopeEarned($query){
return $query->where('amount', '>', 0);
}
public function about(){
return $this->hasOne('\App\Point', 'id', 'point_id');
}
}
This way you when deleting the Model or Item you can simply do the below:
// Inject your User in the constructor or function - lets say you names it User $user
$user->points->delete();
I suggest you also look at Eloquent's association and sync methods when working with relations this way you always know that the related Models are on sync and there re no orphaned children in the database which in Enterprise Design is a huge problem as accuracy and Data intergrity is everything .
Related
I am using Laravel 5.4. I have 2 tables destination and user and a pivot table destination_user.
destination table
---|------
id | name
---|------
1 | sth
user table
---|------
id | name
---|------
1 | sth
and finally Pivot table
--------------|--------
destination_id| user_id
--------------|--------
1 | 1
2 | 1
3 | 2
I created a model for pivot table named destinationUser.
My destination model looks like this:
<?php
namespace App\models;
use App\Models\User;
use App\Models\DestinationUser;
use App\Models\DestinationImage;
use Illuminate\Database\Eloquent\Model;
class Destination extends Model
{
protected $table = 'destinations';
public function user() {
return $this->belongsToMany('App\Models\User');
}
public function destinationUser() {
return $this->hasMany('App\Models\DestinationUser');
}
}
I want to get all the destinations with their respective user detail using pivot table. I have tried so far is this:
$destinations = $this->destination->with('user', 'destinationUser')
->whereHas('destinationUser', function($query) {
$query->where('user_id', user()->id);})
->paginate(20);
dd($destinations[0]->destinationUser); gives me destination id and user id but I want user detail. How can I achieve this. Thank You for your help
You need a many to many relationship:
class Destination extends Model
{
protected $table = 'destinations';
public function destinationUser() {
return $this->belongsToMany('App\User');
}
}
controller
$destinations = $this->destination->with('destinationUser', function($query) {
$query->where('user.id', user()->id);})
->paginate(20);
As I was searching for faster execution of queries, there was a wrong design of tables. There is more load and time of execution for 3 table with pivot rather than 2 tables without pivot. So, I figured it out and corrected.
I'm trying to figure out how I can do a query within a query. (if that even makes sense) I want to grab all the activities. For each activity I want to get the count of users that did the activity. Then I want to order all the activities in DESC order based on the amount of users that did each activity. I'm basically making a "Popular Activities Page" where I show the all activities starting with the activity done by the most users.
I have 3 main tables for this
users
| id | name | password | email | created_at |
activities
| id | title | description | created_at |
resource This is a table I'm using for posts which shows which user did which activity. (Users can show what activities they did, and attach media and locations to the post)
| id | user_id | activity_id | media_id | location_id | created_at |
Here are my models for each table
User Model
class User extends Eloquent {
protected $table = 'users';
/**
* get the activities associated with the given user
* #return mixed
*/
public function activities()
{
return $this->belongsToMany('Acme\Activities\Activity', 'resource', 'activity_id');
}
public function posts(){
return $this->hasMany('Acme\Resource\Resource');
}
public function media()
{
return $this->hasMany('Acme\Media\Media');
}
public function locations()
{
return $this->hasMany('Acme\Locations\Location');
}
}
Activity Model
class Activity extends Eloquent {
protected $table = 'activities';
public function posts(){
return $this->hasMany('Acme\Resource\Resource', 'resource_id');
}
/**
* get the users associated with the given activity card
* #return mixed
*/
public function users()
{
return $this->belongsToMany('Acme\Users\User', 'resource', 'user_id');
}
}
Resource Model
class Resource extends Eloquent {
protected $table = 'resource';
public function user()
{
return $this->belongsTo('Acme\Users\User', 'user_id');
}
public function activities()
{
return $this->belongsTo('Acme\Activities\Activity', 'activity_id');
}
public function media()
{
return $this->hasMany('Acme\Media\Media', 'media_id');
}
public function locations()
{
return $this->belongsTo('Acme\Locations\Location', 'location_id');
}
}
I know I can get all activities using
Activity::get()
I can get a user count for a specific activity using
User::whereHas('resource', function($q) use ($activity_id){
$q->where('activity_id', $activity_id);
})->get()->count();
but I don't know how I can put all of this together in order to get all Activities sorted by user count, starting with the activity with the highest user count.
How would I make this query using eloquent?
Thanks in advance!
try
Resource::select(DB::raw('*, COUNT(distinct(user_id)) as user_count'))->group_by('activity_id')->order_by('user_count', 'desc')->get();
You could then do this
$results = Resource::select(DB::raw('*, COUNT(distinct(user_id)) as user_count'))->group_by('activity_id')->order_by('user_count', 'desc')->get();
foreach ($results as $result) {
$activity = Activity::where('id','=',$result->activity_id)->first();
// do stuff to display data for this activity like
// $activity->title or $activity->description
$count = $result->user_count;
}
I have a User table and need to allow for users to have a parent user.
the table would have the fields:
id
parent_id
email
password
How would I define this self referencing relationship in Eloquent ORM?
I had some success like this, using your exact DB table.
User Model:
class User extends Eloquent {
protected $table = 'users';
public $timestamps = false;
public function parent()
{
return $this->belongsTo('User', 'parent_id');
}
public function children()
{
return $this->hasMany('User', 'parent_id');
}
}
and then I could use it in my code like this:
$user = User::find($id);
$parent = $user->parent()->first();
$children = $user->children()->get();
Give that a try and let me know how you get on!
I had a chain of self referencing contracts (a contract can be continued by another contract) and also needed self referencing. Each contract has zero or one previous and also zero or one next contract.
My data table looked like the following:
+------------------+
| contracts |
+------------------+
| id |
| next_contract_id |
+------------------+
To define the inverse of a relationship (previous contract) you have to inverse the related columns, that means setting
* foreign key column on the model table
* associated column on the parent table (which is the same table)
<?php namespace App;
use Illuminate\Database\Eloquent\Model;
class Contract extends Model {
// The contract this contract followed
function previousContract()
{
// switching id and next_contract_id
return $this->belongsTo('App\Contract', 'id', 'next_contract_id');
}
// The contract that followed this contract
function nextContract()
{
return $this->belongsTo('App\Contract');
// this is the same as
// return $this->belongsTo('App\Contract', 'next_contract_id', 'id');
}
}
See http://laravel.com/docs/5.0/eloquent#one-to-one for further details.
I am making user to user messaging system in laravel 4. So in a simplified version i have to table
First table
Users
user_id |
user_name
Second table
Messages
message_id |
message_from_user_id |
message_to_user_id |
message_content |
So after reading the documentation I learned that User has many message and message belongs to User.
But how do I actually relate them in coding?
I am quite confused how will I use the foreign key in this case for a message that will have two user?
Check this out: http://laravel.com/docs/eloquent#many-to-many
Basically you need a table structure like this
Users: id | username
Messages: id | from | content
user_messages: user_id | message_id
You can define your models like this
class User extends Eloquent {
public function messages()
{
return $this->belongsToMany('Message');
}
public function sent_messages()
{
return $this->hasMany('Messages', 'from');
}
}
class Message extends Eloquent {
public function from()
{
return $this->belongsTo('User', 'from');
}
public function to()
{
return $this->belongsToMany('User');
}
}
Im really new to laravel, and im sure im doing something wrong
I have 2 tables. Cities And users_metadata
My cities table look like this
id | City |
1 | New York |
1 | Los Angeles |
users metadata
user_id | firt name | last name | cities_id |
1 | Jonh | Doe | 2 |
So my problem is when i create a relation i get New York, becaus the city id is matched with the user id
City model
class City extends Eloquent
{
public static $table = "cities";
public function profile()
{
return static::has_many('Profile');
}
}
profile model
class Profile extends Eloquent
{
public static $timestamps = false;
public static $table = "users_metadata";
public static $key = "user_id";
public function city()
{
return static::has_one('City');
}
}
error
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'profile_id' in 'where clause'
SQL: SELECT * FROM `cities` WHERE `profile_id` = ? LIMIT 1
Bindings: array (
0 => 1,
)
If i dont pass the id to has one i get the following error
Okay i understand this.
So my questions is am i able to pass the foreign key cities_id somehow in my relation to match? Or im doing it all wrong? Can someone give me a basic example?
thank you folks
Try this:
City model
class City extends Eloquent
{
public static $table = "cities";
public function profile()
}
Profile model
class Profile extends Eloquent
{
public static $timestamps = false;
public static $table = "users_metadata";
public static $key = "user_id";
public function city()
{
return static::belongs_to('City');
}
}
I ran into the same problem thinking I should use has_one, but I needed to use belongs_to. user1808639's probably didn't work because you still had a 'has_many' in the city model.
Try this:
class Profile extends Eloquent
{
public function city()
{
return $this->belongs_to('City'); // city_id in the table
}
}
Laravel has a way of detecting foreign keys automatically. So for your database schema... this models should work fine
Try the following
user_id | firt name | last name | city_id | //city not cities
1 | Jonh | Doe | 2 |
-
class Profile extends Eloquent
{
public static $timestamps = false;
public static $table = "users_metadata";
public function city()
{
return $this->has_one('City');
}
}
/
class City extends Eloquent
{
public static $timestamps = false;
public function profiles()
{
return $this->has_many('Profile');
}
}
The table rows shouldn't contain whitespaces. So rename "firt name" | "last name" in "firstname" | "lastname". The SQL-error shows me that you're calling the model in the reverse way like City::find(1) in this case Laravel expects inside the "Cities" table the foreign key for the profiles that would be usually "profile_id".
I guess you're looking for something like this:
$user_id = 1;
$user = Profile::find($user_id);
echo $user->firstname." ".$user->lastname." lives in ".$user->city->city;