I have a one to many relationships in the database, and I am trying to extract the latest. The table names are notification and alertFrequency, they have models for each. I want to write a query that will get me the latest time stamp associated to a specific website in the notifications table. The alertFequency table has only 2 columns namely notification_id and created_at. the following are my model notification modl
class Notification extends Model
{
protected $fillable = ['id','website_url','email','slack_channel','check_frequency','alert_frequency','speed_frequency','active'];
public function statuses(){
return $this->belongsToMany('App\Status')->withPivot('values')->withTimestamps();
}
public function alertFrequencies(){
return $this->hasMany('App\AlertFrequency');
}
// trail versions
public function alert(){
$items = AlertFrequency::select('alertFrequencies.created_at')//Any column you want to fetch
->join('notifications', 'notifications.id', '=', 'alertFrequencies.notification_id')
->orderBy('alertFrequencies.created_at','desc')
->first();
if($items == null){
return null;
}
return $items->created_at->toDateTimeString();
class AlertFrequency extends Model{
protected $table = 'alertFrequencies';
public function notification(){
return $this->belongsTo('App\Notification');
}
}
inside the notification model i wrote a function that is expected to extract the data(i.e the latest time stamp of a specific website in the notification table) more over the notification_id is a foreign key in the alertFrequency table. the alert function is as follows
public function alert(){
$alert_timestamp = AlertFrequency::with('notification')->select('created_at')->orderBy('created_at','desc')->first();
//$alert_timestamp=$alert_timestamp->created_at->toDateTimeString();
if($alert_timestamp==null){
return false;
}
return $alert_timestamp;
}
it is returnning created_at time stamp but not the latset related to a specific website. i would apperciate your help?
in the database i have two websites added one at 12:18 and the second ata 12:24..... sorry i dont know how i can post the database here.
Directly You can not apply orderBy() on relation you need to use join()
Just try this. Hope it helps
$alert_timestamp = AlertFrequency::select('alertFrequencies.created_at')//Any column you want to fetch
->join('notification', 'notification.notification_id', '=', 'alertFrequencies.notification_id')
->orderBy('alertFrequencies.created_at','desc')
->get();
Related
Database
I'm kind of new to databases and I made this small database, but I have problems fetching data from it.
Im trying to get all the racers from the logged in user, and it works properly, but if I enter $pigeons = $user->racer I only get back the racer table. I would like to know the attributes of the racers from the pigeons table aswell. I've made it work with query builder left joining the tables but I'm not sure why I set up this relationship if I can't use Laravel inner method.
In the User model I have these relationships:
public function pigeons(){
return $this->hasMany('App\Pigeon');
}
public function racers(){
return $this->hasManyThrough('App\Racer', 'App\Pigeon');
}
This is the Pigeon model:
public function user(){
return $this->belongsTo('App\User');
}
public function racer(){
return $this->hasMany('App\Racer');
}
}
And this is the Event model:
public function race(){
return $this->hasOne('App\Race');
}
public function racers(){
return $this->hasMany('App\Racer');
}
And this is what my EventsController looks like with the working alternative method and the commented not working.
public function upcoming(){
$id = auth()->user()->id;
$user = User::find($id);
$pigeons = DB::table('racers')->leftJoin('pigeons', 'racers.pigeon_id', '=', 'pigeons.id')->where('pigeons.user_id', '=', $id)->get();
//$pigeons = $user->racers;
return view('events.upcoming')->with('pigeons', $pigeons);
}
This is what I get with $user->racers or $user->racers()->get():
[{"id":1,"pigeon_id":14,"user_id":4,"event_id":1,"position":0,"created_at":null,"updated_at":null},{"id":2,"pigeon_id":15,"user_id":4,"event_id":1,"position":0,"created_at":null,"updated_at":null},{"id":3,"pigeon_id":16,"user_id":4,"event_id":1,"position":0,"created_at":null,"updated_at":null}]
And this is what I want to get, its not correct either since I should get id:1 but I want to pass to view these additional datas aswell like gender, color, ability (but they are in pigeons table not in racers).
[{"id":14,"pigeon_id":14,"user_id":4,"event_id":1,"position":0,"created_at":"2018-09-27 10:01:04","updated_at":"2018-09-27
10:01:04","gender":"hen","color":"blue","ability":38},{"id":15,"pigeon_id":15,"user_id":4,"event_id":1,"position":0,"created_at":"2018-09-27 10:01:04","updated_at":"2018-09-27
10:01:04","gender":"hen","color":"blue","ability":48},{"id":16,"pigeon_id":16,"user_id":4,"event_id":1,"position":0,"created_at":"2018-09-27 10:01:04","updated_at":"2018-09-27
10:01:04","gender":"cock","color":"blue","ability":11}]
To get the pigeons, what you would have to do is $pigeons = $user->racers()->get();. You can see an example of this in Laravel's official documentation https://laravel.com/docs/5.5/eloquent-relationships#introduction.
This is my Report Model
protected $fillable = [
'site_url',
'reciepients',
'monthly_email_date'
];
public function site()
{
return $this->belongsTo('App\Site');
}
This is my Site Model
public function report()
{
return $this->hasMany('App\Report');
}
This is my ReportController
public function showSpecificSite($site_name)
{
$records = DB::table('reports')
->select('email_date','url','recipient')
->whereHas('sites', function($query){
$query->where('site_name',$site_name);
})
->get();
return view('newsite')->with('records',$records)
->with('site_name',$site_name);
}
My Controller is not yet working as well.
The thing is I would like to copy all the three files from sites table to reports table.
Is it possible in insertInto ?
My code on ReportController shows you that I'm selecting data from reports table but I am the one who puts data to reports table to see the output but it is not yet working because of the it cant reach out the value of site_name even though I already put a relationship between the two tables.
You're not actually using Eloquent in your controller you're just using the Query Builder (DB). This will mean that you don't have access to anything from your Eloquent models.
Try:
$records = \App\Report::whereHas('site', function($query) use($site_name) {
$query->where('site_name', $site_name);
})->get(['id', 'email_date', 'url', 'recipient']);
I've added id to the list of columns as I'm pretty sure you'll need that to use whereHas.
NB to use a variable from the parent scope inside a closure you need to pass it in using use().
I am facing issue regarding storing ids and display their values from two different table i have 1 table business_master and other table is page_master i have combine business_name column with page_url column which are available on page_master table if i add my business and page first time its successfully combine these two values as one business can have many pages and if i only add page 2nd time i am unable to see business_url with page_url column.
My Page Model:
class PageList extends Model
{
protected $table = 'page_master';
protected $fillable = ['business_id', 'page_url', 'page_name'];
public function business()
{
return $this->hasOne('App\Business','business_id');
}
}
and in my view:
<td>{{optional($value->business)->business_url}}.spikesales.io/{{$value->page_url}}</td>
This is my first time out if i add business_url and page_url
hussain.spikesales.io/house
and then if i add only page the out put is something like that
.spikesales.io/hello
one business can have many page it should attach business_ url also but i am unable to find solution:
Any help will be highly appreciated!
public function pageListHere()
{
$list = PageList::all();
return view('page-list',compact('list'));
}
You have to change your controller code like this:
$list = PageList::select('*');
$list->with(
array('business'=>function($query){
$query->select('*');
}));
$pageList = $list->get();
return view('page-list',compact('pageList'));
The varialbe $pageList will be having all the rows of that table along with related Business table rows.
I have 3 tables: orders, codes, events
I want to be able to pull all events that an order has, but there's an intermediary table that acts as a pivot table. I've been trying to use hasManyThrough and belongsToMany (along with withPivot) without any luck.
Examples:
public function events()
{
return $this->belongsToMany('events'); // tried this, fails
return $this->hasManyThrough('events', 'codes'); // tried this, fails
return $this->hasManyThrough('events', 'codes', 'event_id', 'id'); // tried this, fails
}
Any pointers would be great!
That's a belongsToMany setup. First, the first parameter is the name of the related class. Second, since your pivot table doesn't follow the Laravel naming conventions, you need to specify the name of the pivot table in your relationship definition:
public function events()
{
// first parameter is the name of the related class
// second parameter is pivot table name
return $this->belongsToMany(Event::class, 'codes');
}
With this setup, you can do:
// get an order
$order = Order::first();
// has all the events related to an order
$events = $order->events;
There are many ways to do this. I will show a one you can get it done.
In Order.php model
public function codes(){
return $this->has('App\Http\Code');
}
In Code.php model
public function orders(){
return $this->belongsTo('App\Http\Order');
}
public function events(){
return $this->hasMany('App\Http\Event');
}
In Event.php model
public function codes(){
return $this->belongsTo('App\Http\Code');
}
Then in you Controller, call them to get required data.
In your case you can do it like below:
$orders = Order::with(['codes' => function($q){
$q->with('events');
})->get();
May be you can get them with nested manner(not sure about this because i didn't tried before posting):
$orders = Order::with('codes.events')->get();
put return $orders; in your controller to see the query.
Enjoy!
How wherePivot() actually works internally in laravel 5 ?
For Example I was practicing by watching a tutorial and the teacher was using wherePivot() for construing relationship:
public function friendsOfMine(){
return $this->belongsToMany('Chatty\Models\User','friends','user_id','friend_id');
}
public function friendOf(){
return $this->belongsToMany('Chatty\Models\User','friends','friend_id','user_id');
}
public function friends(){
return $this->friendsOfMine()->wherePivot('accepted',true)->get()->merge($this->friendOf()->wherePivot('accepted',true)->get());
}
Thanks Guys .. but I think i found my answer
A pivot table is a database table that only exists to serve a many-to-many relationship. Say you have a table “customer” and a table “drinks”. If you want to know which customer ordered which drink you have to create a pivot table customer_drinks(customer_id, drink_id).
Define Pivot table
class Customer extends \Eloquent {
public function drinks()
{
return $this->belongsToMany('Drink', 'customer_drinks', 'customer_id', 'drink_id');
}
}
Create a Record
$customer = Customer::find($customer_id);
$customer->drinks()->attach($drink_id); //this executes the insert-query
Remove record from pivot Table
$customer = Customer::find($customer_id);
$customer->drinks()->detach($drink_id); //this executes the delete-query on the pivot table